【发布时间】:2019-11-28 05:26:38
【问题描述】:
我正在尝试使用 str_detect 和 case_when 根据多种模式重新编码字符串,并将每次出现的重新编码值粘贴到一个新列中。正确的列是我想要实现的输出。
这类似于this question 和this question 如果不能用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
Num Fruit Correct
1 Apples good
2 apples, maybe bananas good,gross
3 Oranges ok
4 grapes w apples ok,good
5 pears other
【问题讨论】: