如何使用str_detect组合设置关键词包含、排除的匹配规则
代码调整方案
你需要在匹配规则里同时叠加「包含指定关键词」和「排除指定关键词」两个判断条件即可,调整后的代码如下:
library(magrittr) library(dplyr) library(stringr) data <- data.frame(name = c("john A", "john B", "john C","John A")) data %<>% mutate(john_AB = case_when( # 同时满足:包含大小写不敏感的john + 不包含C,才赋值为1 str_detect(name, regex("john", ignore_case = TRUE)) & !str_detect(name, "C") ~ 1, TRUE ~ 0 ))
逻辑说明
- 用
regex("john", ignore_case = TRUE)替代原来的john|John写法,更简洁的实现大小写不敏感的匹配 - 通过
&符号叠加!str_detect(name, "C")的否定判断,实现排除包含指定关键词的行 - 如果你的排除规则仅针对完整的
john C(允许其他带C的john行),可以把排除条件改为!str_detect(name, regex("john C", ignore_case = TRUE)),匹配更精准
简化写法(可选)
因为你的判断结果是0/1二元值,可以不用case_when,直接把逻辑值转成整数即可:
data %<>% mutate(john_AB = as.integer(str_detect(name, regex("john", ignore_case = TRUE)) & !str_detect(name, "C")))
内容的提问来源于stack exchange,提问作者user224050
相关产品推荐
相关产品推荐

