嵌套ifelse引用向量中的元素

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>
> 
评论
非主流网名
非主流网名

寻找这个吗?

df$group <- ifelse(df$Var1  %in% AB, "AB Group",
                   ifelse(df$Var1  %in% CD, "CD Group", NA)) # If not AB or CD -> NA
点赞
评论
dsit
dsit

以下解决方案似乎有效。

df$group <- ifelse(
    is.element(df$Var1, AB), "AB Group",
    ifelse(is.element(df$Var1, CD), "CD Group", NA))

我希望这有帮助!

点赞
评论
舒灵波
舒灵波

You can use case_when from dplyr wherein it is easy to add more conditions.

If none of the condition match, it automatically assigns NA to it.

library(dplyr)

df %>%
  mutate(group = case_when(Var1 %in% AB ~ 'AB Group', 
                           Var1 %in% CD ~ 'CD group'))


#    Var1    group
#1      A AB Group
#2      A AB Group
#3      F     <NA>
#4      A AB Group
#5      B AB Group
#6      E     <NA>
#7      D CD group
#8      C CD group
#9      F     <NA>
#10     C CD group
#....
点赞
评论