我有一个数据框,上面有动物的名字

x=data.frame(c("lion","tiger","cow","vulture","hyena","leopard","deer","gazzelle"))
colnames(x)=c('animal')

#create sets of animals based on the their diet

carnivore=c("lion","tiger","leopard")
herbivore=c("cow","deer","gazzelle")
omnivore=c("vulture","hyena")

x$diet=NA   ## Add a new column where I want to enter if the animal is one of herbivore, carnivore or omnivore based on the value in x$animal

for (i in 1:(nrow(x))) {
  if (x$animal[i] 'is a subset of' "Omnivore") {
    x$diet[i] = "Omnivore"
  } else if (x$animal[i] 'is a subset of' "Carnivore") {
    x$diet[i] = "Carnivore"
  } else if (x$animal[i] 'is a subset of' "Herbivore") {
    x$diet[i] = "Herbivore"
  }
}





    

我不太能在R中编写等同于‘is a subset’的代码,我相信它肯定有一个简单的解决方案.如有任何帮助,不胜感激

推荐答案

您的现有代码需要%in% operator:

for (i in 1:(nrow(x))) {
  if (x$animal[i] %in% omnivore) {
    x$diet[i] = "Omnivore"
  } else if (x$animal[i] %in% carnivore) {
    x$diet[i] = "Carnivore"
  } else if (x$animal[i] %in% herbivore) {
    x$diet[i] = "Herbivore"
  }
}

我更喜欢嵌套的ifelse(),而不是forloop + if{}else{}:

x$diet <- ifelse(x$animal %in% carnivore, "Carnivore",
                 ifelse(x$animal %in% herbivore, "Herbivore",
                        ifelse(x$animal %in% omnivore, "Omnivore", "Other")))
x
#     animal      diet
# 1     lion Carnivore
# 2    tiger Carnivore
# 3      cow Herbivore
# 4  vulture  Omnivore
# 5    hyena  Omnivore
# 6  leopard Carnivore
# 7     deer Herbivore
# 8 gazzelle Herbivore

R相关问答推荐

高质量地将R格式的图表从Word中输出

在特定列上滞后n行,同时扩展框架的长度

列出用m n个值替换来绘制n个数字的所有方法(i.o.w.:R中大小为n的集合的所有划分为m个不同子集)

使用ggplot将平滑线添加到条形图

如何计算前一行的值,直到达到标准?

在R中替换函数中的特定符号

从R导出全局环境中的所有sf(numrames)对象

使用ggsankey调整Sankey图中单个 node 上的标签

根据文本字符串中的值粘贴新列

使用data.table::fcase()而不是dplyr::case_When()时保持值

如何在ggplot2中绘制具有特定 colored颜色 的连续色轮

为什么在BASE R中绘制线条时会看到线上的点?

根据约束随机填充向量的元素

自动STAT_SUMMARY统计与手动标准误差之间的差异

在R中,如何将误差条放置在堆叠的每个条上?

提高圣彼得堡模拟的速度

基于R中的辅助向量中的值有条件地连接向量中的字符串

R将函数参数传递给ggploy

Data.table条件合并

移除y轴断开的geom_bar图的外框