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

在dplyr中检测匹配特定正则表达式的文本并标记符合条件行

为数据框添加条件标记列

需求说明

给数据框新增string_detected列,满足以下任一条件则标记为1,否则为0:

  • 存在前面带空格、作为独立单词的pro(不区分大小写)
  • 存在前面带空格、以certificat开头的术语(如certificate、certification等)
  • 存在任意1位或多位数字

示例数据

df_new <- data.frame(
  given_info=c('SA12 is given','he is Pro writer',
               'she programmed','why not having an ra31',
               'his bag missing', 'pa12 and certificate are given',
               'schedule is ready','certification was awarded',
               'meeting is canceled'))

df_new %>% select(given_info)

数据预览:

given_info
1                  SA12 is given
2               he is Pro writer
3                 she programmed
4         why not having an ra31
5                his bag missing
6 pa12 and certificate are given
7              schedule is ready
8      certification was awarded
9            meeting is canceled

解决方案

使用dplyr和stringr包结合正则表达式实现条件匹配:

library(dplyr)
library(stringr)

# 生成标记列并输出结果
df_result <- df_new %>%
  mutate(
    string_detected = as.integer(
      # 匹配带空格的独立pro(大小写不敏感)
      str_detect(given_info, "\\spro\\b", ignore_case = TRUE) |
      # 匹配带空格的certificat开头术语
      str_detect(given_info, "\\scertificat") |
      # 匹配任意连续数字
      str_detect(given_info, "\\d+")
    )
  )

print(df_result)

输出结果

given_info string_detected
1                  SA12 is given               1
2               he is Pro writer               1
3                 she programmed               0
4         why not having an ra31               1
5                his bag missing               0
6 pa12 and certificate are given               1
7              schedule is ready               0
8      certification was awarded               1
9            meeting is canceled               0

正则表达式说明

  • \\spro\\b:\\s匹配前置空格,\\b确保pro是独立单词,ignore_case=TRUE实现大小写兼容
  • \\scertificat:\\s匹配前置空格,certificat匹配前缀,自动兼容后续任意衍生字符
  • \\d+:\\d匹配单个数字,+表示匹配1个或多个连续数字

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:05:29