Multiple ifelse statement

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

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

# mock data

#variables for subsetting

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