You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 23:45:04