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

如何在R中为每个关键词单独列统计文本中的出现次数

统计关键词出现次数并生成单独列的解决方案

完整代码实现

先加载tidyverse工具包,再结合dplyr和stringr完成统计需求:

library(tidyverse)

# 原数据与关键词向量
df <-  read.table(text= "title     date    text
blablabla   22.07.2023  'blablablabla Blue blablabla'
blablabla   23.06.2023  'bala Blue blabla Blue Night Blue'
blablabla   23.08.2023  'bala Mountain blabla House Night Blue'", 
header = T, stringsAsFactor = F) 

words <- c("House", "Mountain", "Blue", "Night")

# 生成关键词计数列
df_result <- df %>%
  mutate(across(all_of(words), ~str_count(text, fixed(.x))))

# 查看最终结果
print(df_result)

代码说明

  • across(all_of(words)):遍历关键词向量中的每个元素,为每个关键词自动生成对应的统计列
  • str_count(text, fixed(.x)):str_count负责统计text列中当前关键词的出现次数,fixed(.x)用于精确匹配关键词(避免正则表达式特殊字符干扰,适合关键词含特殊符号的场景)

输出结果

title       date                                         text House Mountain Blue Night
1 blablabla 22.07.2023                'blablablabla Blue blablabla'     0        0    1     0
2 blablabla 23.06.2023        'bala Blue blabla Blue Night Blue'     0        0    3     1
3 blablabla 23.08.2023 'bala Mountain blabla House Night Blue'     1        1    1     1

扩展:不区分大小写匹配

如果需要忽略大小写统计(比如Blue和blue都计入次数),只需把fixed(.x)替换为regex(.x, ignore_case = TRUE):

df_result <- df %>%
  mutate(across(all_of(words), ~str_count(text, regex(.x, ignore_case = TRUE))))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:30:11