【问题标题】:How to code for multiple ‘or’ conditions in an ifelse command for a dataframe in R如何在 ifelse 命令中为 R 中的数据帧编写多个“或”条件
【发布时间】:2021-09-29 10:34:49
【问题描述】:

我对 R 比较陌生,我正在尝试向数据框(称为 dGroup)添加一列,这取决于数据框中现有列(物种)中指定的名称。 在 dGroup 列中指定了属于三个组中的每个组的许多物种。这些是“Mus (Mouse)”或“Cerc (Possum)”应该在 dGroup 列中生成一个“SM”,“Tri (Brush tail)”或“Thyl (Wallaby)”或“Mac (Bennetts)”应该生成一个dGroup 列中的“MM”和“Mac (Bennetts)”应在 dGroup 列中生成“LM”。 数据框如下所示:

|Record|Species|        dGroup|
|------|--------|-------|
|1|     Mus (Mouse)|
|2|     Cerc (Possum)|
|3|     Tri (Brush tail)
|4|     Thyl (Wallaby)
|5|     Vom (Wombat)
|6|     Mac (Bennetts)

我使用的代码如下: #import csv 确保字符串保留

    df <- read.csv(file = 'SH.csv', stringsAsFactors=FALSE)

#add a new column to the dataframe called dGroup

    df['dGroup']<-NA

#test with a single species note: this code words

    df$dGroup = ifelse(df$Species == "Mus (Mouse)","SM", "NA")

#test combine two species in an ‘or’ condition note: this code does not work

    df$dGroup = ifelse(df$Species == "Mus (Mouse)"||df$Species=="Cerc ( Possum)"){"SM", “NA”)}

我收到以下错误: 错误:意外的“{”在 有人可以帮忙吗?

【问题讨论】:

    标签: r dataframe if-statement conditional-statements


    【解决方案1】:
    library(dplyr)
    library(magrittr)
    

    在数据框中生成 (mutate) 新变量 (dGroup) 时,您可以使用 case_when 命令

    df <- df %>%
      mutate(dGroup = case_when(Species == "Mus (Mouse)" ~ "SM",
                                Species == "Cerc (Possum)" ~ "SM"))
    

    您可以继续填写其他物种的条件。这是case_when 上的一个很好的资源:@​​987654321@

    【讨论】:

    • 衷心感谢,因为建议 case_when 和 mutate 是解决我问题的好方法。
    【解决方案2】:

    你在找这个吗?

    df %>% mutate(dGroup = ifelse(Species %in% c("Mus (Mouse)", "Cerc (Possum)"), "SM", NA))
    

    【讨论】:

    • 非常感谢,建议的代码有效,但是我的数据框可能包含太多行,因为运行它后我收到了以下 '[达到'max' / getOption("max.print") -- 省略 8910 行 ]'。
    猜你喜欢
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2014-12-22
    相关资源
    最近更新 更多