
[英]How to create a dummy variable in R with multiple conditions using ifelse() command
[英]How to code for multiple ‘or’ conditions in an ifelse command for a dataframe in R
我对 R 比较陌生,我正在尝试向数据帧(称为 dGroup)添加一列,该列以数据帧中现有列(物种)中指定的名称为条件。 有许多物种将属于要在 dGroup 列中指定的三个组中的每一个。 它们是“Mus(鼠标)”或“Cerc(负鼠)”应在dGroup列中生成“SM”,“Tri(刷尾)”或“Thyl(Wallaby)”或“Mac(Bennetts)”应生成一个“SM” 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”)}
我收到以下错误:错误:意外的“{”有人可以帮忙吗?
你在找这个吗?
df %>% mutate(dGroup = ifelse(Species %in% c("Mus (Mouse)", "Cerc (Possum)"), "SM", NA))
library(dplyr)
library(magrittr)
您可以在数据帧中生成( mutate
)新变量 ( dGroup
) 时使用case_when
命令
df <- df %>%
mutate(dGroup = case_when(Species == "Mus (Mouse)" ~ "SM",
Species == "Cerc (Possum)" ~ "SM"))
您可以继续填写其他物种的条件。 这是关于case_when
一个很好的资源: https : case_when
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.