# 嵌套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

``````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
#....
``````