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

R语言如何将数据框评论列匹配的关键词写入新列

解决方法

你之前使用的grepl仅返回是否匹配的逻辑值,要提取实际匹配到的关键词,可以用以下两种方案实现:


方案1:仅用R基础包实现

# 定义关键词和匹配规则
keywords <- c('poor communication', 'email', 'tools', 'hardware', 'software')
match_pattern <- paste0(keywords, collapse = '|')

# 提取匹配关键词并写入Topic列
df$Topic <- sapply(
  regmatches(df$Comment, gregexpr(match_pattern, df$Comment, ignore.case = TRUE)),
  function(matches) {
    if (length(matches) == 0) return(NA_character_) # 无匹配时返回NA,可自行替换为空字符串""
    paste(unique(matches), collapse = ", ") # 匹配到多个关键词时用逗号分隔,加unique避免重复
  }
)

方案2:tidyverse生态实现(代码更简洁)

依赖dplyr和stringr包:

library(dplyr)
library(stringr)

keywords <- c('poor communication', 'email', 'tools', 'hardware', 'software')
match_pattern <- paste0(keywords, collapse = '|')

df <- df %>%
  mutate(
    Topic = str_extract_all(Comment, match_pattern) %>%
      sapply(function(x) if(length(x) == 0) NA_character_ else paste(unique(x), collapse = ", "))
  )

补充说明

如果需要忽略大小写匹配,只需调整匹配规则:

  • 基础包方案:给gregexpr加参数ignore.case = TRUE
  • tidyverse方案:把match_pattern替换为regex(match_pattern, ignore_case = TRUE)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:45:04