I'm trying to use nested ifelse
passing a list of elements in two vectors. Specifically, I would like to achieve the following goal:
set.seed(101)
df <- data.frame("Var1" = sample(c("A", "B", "C", "D", "E", "F"), size=100, replace = TRUE))
# Group A or B
AB <- c("A", "B")
# Group C or D
CD <- c("C", "D")
df$group <- ifelse(df$Var1 == AB, "AB Group",
ifelse(df$Var1 == CD, "CD Group", NA)) # If not AB or CD -> NA
虽然我有:
> head(df)
Var1 group
1 A AB Group
2 A <NA>
3 F <NA>
4 A <NA>
5 B <NA>
6 E <NA>
>
寻找这个吗?
以下解决方案似乎有效。
我希望这有帮助!
You can use
case_when
fromdplyr
wherein it is easy to add more conditions.If none of the condition match, it automatically assigns
NA
to it.