Multiple ifelse statement

Hello,
I am trying to use multiple ifelse statements and would really appreciate some help!

Problem:
I want to add a variable to data frame using multiple following conditions.


# mock data
x<-data.frame(1:3,6:8)

#variables for subsetting
b<-c('A','B')
d<-c('d','e')

# creating dataframe.
# If coloumb X1.3 contains b then I want the new variable 'help' to contain "rich". 
# If coloumb X1.3 contains d  then I want the new variable 'help' to contain "poor".  
# And if coloumb X1.3 doese not contain either d or b then i want 'help to contain 'middle'.
# I tried the following but no sucess. 

Data_Frame <- x %>% 
mutate(Help = ifelse(x$X1.3 %in% b , 'Rich',       
              ifelse(x$X1.3 %in% d , 'Poor', 
              ifelse(!x$X1.3 %in% d|b , 'Middle'))

Thank you !!!

When you are mutating x then you should not reference the variables in x with x$ before them.
For multiple cases use dplyr case_when

Thank you for your reply!

I have worked it out.
There was issues with the mockup code. Thank you for pointing this out!

I also used a solution on this website

Alternatively, you could use case_when() to replace the multiple ifelse(). This is one of my favorite commands that dplyr brings to the table. So it could be:

table %>%
  mutate(
     help = case_when(
           x %in% b ~ "Rich",
           x %in% d  ~ "Poor",
           TRUE ~ "Middle"
)
1 Like

Thank you!!
This is super helpful:)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.