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

使用tidyverse判断列是否含指定列表词汇:修正无效代码求助

问题与修正方案

问题背景

我有一个名为df的表格:

title             date            brand
big farm house    2022-01-01      A
ranch modern      2022-01-01      A
town house        2022-01-01      C

另有一个名为match_list的表格,存储需要匹配的关键词:

words_for_match
farm
town
clown
beach
city
pink

想要用mutate新增一列,当title包含match_list里的任意词汇时标记为"Yes",否则为"No"。但尝试的代码全部返回"No",代码如下:

match_list <- match_list$words_for_match

match_list <- paste(company_names_list, collapse = "|")

df %>% 
   mutate(Flag = ifelse(str_detect(title, fixed(as.character(match_list))), "Yes", "No"))

修正后的代码

你的代码有两处关键错误,修正后即可正常运行:

  1. 拼接正则时误用了不存在的company_names_list变量,应该用提取后的match_list向量
  2. 使用fixed()会把拼接的"|"当成普通字符匹配,而非正则的"或"逻辑,需移除fixed()

完整修正代码:

library(dplyr)
library(stringr)

# 提取关键词并拼接成正则匹配式
match_pattern <- paste(match_list$words_for_match, collapse = "|")

# 新增标记列
df <- df %>% 
  mutate(Flag = ifelse(str_detect(title, match_pattern), "Yes", "No"))

运行后得到的df结果:

title             date            brand Flag
big farm house    2022-01-01      A     Yes
ranch modern      2022-01-01      A     No
town house        2022-01-01      C     Yes

额外优化

如果需要精确匹配完整单词(比如不想把farmer里的farm识别为匹配),可以把正则改成带单词边界的形式:

match_pattern <- paste0("\\b", match_list$words_for_match, "\\b", collapse = "|")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:41:08