我正在尝试使用 str_detect 和 case_when 根据多个模式重新编码字符串,并将重新编码的值的每次出现粘贴到新列中。正确列是我试图实现的输出。
这类似于this question和this question If it can't be done with case_when (仅限于我认为的一种模式)有没有更好的方法可以仍然使用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
Run Code Online (Sandbox Code Playgroud)
Num …Run Code Online (Sandbox Code Playgroud)