我正试图根据共性对物种进行分类。有4个分类:
1.稀有-频率<平均值&相对丰度<平均值
1.偶然-频率<平均值&相对丰度>平均值
1.常见频率>平均值&相对丰度<平均值
1.优势频率>平均值和相对丰度>平均值
我试图创建一个if else语句,将具有这些分类的列添加到数据框中,如下所示
species <- c("a", "b", "c", "d", "e", "f")
relabund <- c(.5, .11, .23, .06, .36, .19) #relative abundance
freq <- c(6, 3, 20, 2, 11, 4) #number of sites species occurs at
df = data.frame(species, relabund, freq)
字符串
我试过这样的方法:
if (df[,2]>mean(relabund) && df[,3]>mean(freq)) {
df$Classification = "Dominant"
} else if (df[,2]<mean(relabund) && df[,3]<mean(freq)) {
df$Classification = "Rare"
} else if (df[,2]<mean(relabund) && df[,3]>mean(freq)) {
df$Classification = "Common"
} else
df$Classification = "Occasional"
型
但这并不起作用,因为它将所有物种归类为“稀有”。我对if else语句非常陌生,因此任何帮助都将不胜感激。
谢谢你,谢谢
2条答案
按热度按时间np8igboo1#
我用你的代码就能得到“偶尔”
您的
if
语句正在查看逻辑向量,但为所有行返回一个值,例如:df[,2]
是整列:0.50 0.11 0.23 0.06 0.36 0.19
df[,2]>mean(relabund)
返回逻辑向量:TRUE FALSE FALSE FALSE TRUE FALSE
通过使用
&&
,您正在对两个逻辑向量执行逻辑比较。由于这些向量不相同,您总是得到false:df[,2]>mean(relabund) && df[,3]>mean(freq)
==
个c(TRUE, FALSE, FALSE, FALSE, TRUE, FALSE) && c(FALSE, FALSE, TRUE, FALSE, TRUE, FALSE)
==
FALSE
此外,
df$Classification
将列设置为相同的值,即它处理的是整个数据集而不是一行一行的。你需要做的是对每一行执行向量操作。使用
tidyverse
中的dplyr
可以得到更容易阅读的答案(对某些人来说!)字符串
62lalag42#
我们可以使用
case_when
,其中if
位于~
的左侧,右侧是您要分配给该条件的值。字符串
输出
型
数据
型