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

如何在R中自动化逐行处理数据集提取句子关键词?

在R中逐行提取语句中的关键词并新增列

首先修正你数据框创建的小错误:代码里的df<-data.frame(a)应该改为df<-data.frame(Sentences),否则会因找不到对象a报错。

以下是几种实现逐行提取关键词的方案:


方案1:基础R的apply逐行处理

用apply遍历数据框每一行,结合stringr包的str_extract_all(相比你用的str_match,它能提取所有匹配的关键词,更贴合需求),最后把结果整理成字符串:

library(stringr)

# 初始化数据
Sentences<-c("John is playing a video game at the moment","Tom will cook a delicious meal later",
     "Kyle is with his friends watching the game",
     "Diana is hosting her birthday party tomorrow night"
     )
df<-data.frame(Sentences)

keywords<-c("game","is","will","meal","birthday","party")

# 新增匹配关键词列
df$matched_keywords <- apply(df, 1, function(row) {
  # 提取当前行所有匹配的关键词
  matches <- str_extract_all(row, paste(keywords, collapse = "|"))[[1]]
  # 去重后用逗号分隔合并
  paste(unique(matches), collapse = ", ")
})

方案2:tidyverse风格的逐行处理

如果习惯用dplyr的管道语法,用rowwise()实现逐行逻辑更直观:

library(dplyr)
library(stringr)

df <- df %>%
  rowwise() %>%
  mutate(matched_keywords = {
    matches <- str_extract_all(Sentences, paste(keywords, collapse = "|"))[[1]]
    paste(unique(matches), collapse = ", ")
  }) %>%
  ungroup()

如果你坚持用str_match

str_match仅返回第一个匹配项,若要保留你的原始思路,可调整为:

df$matched_keywords <- apply(df, 1, function(row) {
  matches <- na.omit(str_match(row, paste(keywords, collapse = "|")))[,1]
  paste(unique(matches), collapse = ", ")
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:50:34