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'))
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"
)