I'm trying to use str_detect and case_when to recode strings based on multiple patterns, and paste each occurance of the recoded value(s) into a new column. The Correct column is the output I'm trying to achieve.
This is similar to this question and this question If it can't be done with case_when (limited to one pattern I think) is there a better way this can be achieved still using tidyverse?
Fruit=c("Apples","apples, maybe bananas","Oranges","grapes w apples","pears")
Num=c(1,2,3,4,5)
data=data.frame(Num,Fruit)
df= data %>% mutate(Incorrect=
paste(case_when(
str_detect(Fruit, regex("apples", ignore_case=TRUE)) ~ "good",
str_detect(Fruit, regex("bananas", ignore_case=TRUE)) ~ "gross",
str_detect(Fruit, regex("grapes | oranges", ignore_case=TRUE)) ~ "ok",
str_detect(Fruit, regex("lemon", ignore_case=TRUE)) ~ "sour",
TRUE ~ "other"
),sep=","))
Num Fruit Incorrect
1 Apples good
2 apples, maybe bananas good
3 Oranges other
4 grapes w apples good
5 pears other
Num Fruit Correct
1 Apples good
2 apples, maybe bananas good,gross
3 Oranges ok
4 grapes w apples ok,good
5 pears other