Borexino
Borexino

Reputation: 842

Nested ifelse referring to elements in vector

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

While I have:

> head(df)
    Var1   group
1    A   AB Group
2    A     <NA>
3    F     <NA>
4    A     <NA>
5    B     <NA>
6    E     <NA>
> 

Upvotes: 0

Views: 39

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 388817

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

Upvotes: 1

MacOS
MacOS

Reputation: 1159

The following solution seems to work.

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

I hope this helps!

Upvotes: 1

Jan
Jan

Reputation: 5254

Looking for this?

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

Upvotes: 3

Related Questions