R语言 具有多个条件和4个结果的If else语句

oknrviil  于 2023-07-31  发布在  其他
关注(0)|答案(2)|浏览(112)

我正试图根据共性对物种进行分类。有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语句非常陌生,因此任何帮助都将不胜感激。
谢谢你,谢谢

np8igboo

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可以得到更容易阅读的答案(对某些人来说!)

library(tidyverse)

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)

df %>% 
  mutate(classify = 
           ifelse(freq < mean(freq) & relabund < mean(relabund),
                  "Rare",
           ifelse(freq < mean(freq) & relabund > mean(relabund),
                  "Occaisonal",
           ifelse(freq > mean(freq) & relabund < mean(relabund),
                 "Common",
           ifelse(freq > mean(freq) & relabund > mean(relabund),
                 "Dominant",
                 "ERROR")))))

字符串

62lalag4

62lalag42#

我们可以使用case_when,其中if位于~的左侧,右侧是您要分配给该条件的值。

library(tidyverse)

df %>% 
  mutate(classify = case_when(freq < mean(freq) & relabund < mean(relabund) ~ "Rare",
                              freq < mean(freq) & relabund > mean(relabund) ~ "Occaisonal",
                              freq > mean(freq) & relabund < mean(relabund) ~ "Common",
                              freq > mean(freq) & relabund > mean(relabund) ~ "Dominant",
                              TRUE ~ "ERROR"))

字符串

输出

species relabund freq   classify
1       a     0.50    6 Occaisonal
2       b     0.11    3       Rare
3       c     0.23   20     Common
4       d     0.06    2       Rare
5       e     0.36   11   Dominant
6       f     0.19    4       Rare

数据

df <- structure(list(species = c("a", "b", "c", "d", "e", "f"), relabund = c(0.5, 
0.11, 0.23, 0.06, 0.36, 0.19), freq = c(6, 3, 20, 2, 11, 4)), class = "data.frame", row.names = c(NA, 
-6L))

相关问题