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

如何将多列字符串作为gsub匹配模式生成incorrect列?

解决方法:提取未匹配目标词的内容到新列

你需要在已有的recall数据框中添加incorrect列,该列保留written列里没有被匹配到target.apple和target.banana中的单词。

现有代码

recall <- data.frame(written = c("apples car banana hat pencil r", 
                                 "papeer apple cars spoon", 
                                 "dice banaana pen f apple berry"))
recall <- recall %>% mutate(target.apple = str_extract(written,"app([^ ]+)"),
                            target.banana = str_extract(written,"bana([^ ]+)"))

实现代码

通过按行拆分字符串、过滤目标词、重新拼接的方式实现,结合dplyr和stringr工具包处理每一行数据:

library(dplyr)
library(stringr)

recall <- recall %>%
  rowwise() %>%
  mutate(
    # 收集需要移除的非NA目标词
    remove_words = c(target.apple, target.banana)[!is.na(c(target.apple, target.banana))],
    # 拆分文本为单词列表,过滤掉目标词后重新拼接
    incorrect = str_c(setdiff(str_split(written, "\\s+")[[1]], remove_words), collapse = " ")
  ) %>%
  ungroup() %>%
  select(-remove_words)  # 移除临时中间列

运行结果

执行后得到的数据框如下:

written target.apple target.banana           incorrect
1   apples car banana hat pencil r       apples        banana    car hat pencil r
2          papeer apple cars spoon        apple          <NA>   papeer cars spoon
3 dice banaana pen f apple berry        apple       banaana    dice pen f berry

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:55:32