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

如何按id分组统计DataFrame中文本的总词数?

按ID分组统计文本总词数的R实现

问题背景

给定如下R语言DataFrame,需要按id字段分组,统计每个分组下所有文本的总词数:

df <- data.frame(id=rep(1:3, 2), tx=c("test one. test two", "this is a test. again test", "test two", "test three times", 
                                      "test, in a future time point", "test has completed, at the final time point"))

期望输出结果:

id  word count
1   7
2   12
3   10

解决方案

方法1:使用tidyverse工具链(推荐)

借助dplyr的分组功能和stringr的单词统计函数,简洁高效:

# 安装并加载tidyverse(首次使用需安装)
# install.packages("tidyverse")
library(tidyverse)

# 分组统计总词数
result <- df %>%
  group_by(id) %>%
  summarize(`word count` = sum(str_count(tx, "\\w+")))

# 输出结果
print(result)

原理说明:

  • str_count(tx, "\\w+"):匹配文本中的连续字母/数字(自动忽略标点),统计每行的单词数量
  • group_by(id):按id分组
  • sum(...):对每个分组的单词数求和,得到总词数

方法2:使用Base R(无需额外包)

适合不想加载第三方包的场景:

# 原始数据
df <- data.frame(id=rep(1:3, 2), tx=c("test one. test two", "this is a test. again test", "test two", "test three times", 
                                      "test, in a future time point", "test has completed, at the final time point"))

# 步骤1:计算每行文本的单词数
# 先移除标点,再按空格分割,最后统计有效单词数量
df$word_num <- sapply(strsplit(gsub("[^A-Za-z0-9 ]", "", df$tx), "\\s+"), function(x) length(x[x != ""]))

# 步骤2:按id分组求和
result_base <- aggregate(word_num ~ id, df, sum)
colnames(result_base)[2] <- "word count"

# 输出结果
print(result_base)

原理说明:

  • gsub("[^A-Za-z0-9 ]", "", df$tx):移除所有非字母、数字和空格的字符(即标点)
  • strsplit(..., "\\s+"):按一个或多个空格分割文本
  • length(x[x != ""]):排除分割后产生的空字符串,统计有效单词数
  • aggregate(word_num ~ id, df, sum):按id分组对单词数求和

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:47:20