r - 需要计算 R # 列中预先指定的单词
问题描述
我需要计算以下单词\短语在一列中出现的次数:
- 家
- 大满贯
- 分数
这是行形式的输入:
[1] "Ian Desmond hits an inside-the-park home run (8) on a line drive down the right-field line. Brendan Rodgers scores. Tony Wolters scores."
[2] "Ian Desmond lines out sharply to center fielder Jason Heyward."
[3] "Ian Desmond hits a grand slam (9) to right center field. Charlie Blackmon scores. Trevor Story scores. David Dahl scores."
[4] "Ian Desmond homers (12) on a fly ball to center field. Daniel Murphy scores."
期望 的输出 我需要的主要输出是找到多少匹配项的计数。例如,在输入行中有九个匹配项。
我尝试使用的代码
text <- c("Ian Desmond hits an inside-the-park home run (8) on a line drive down the right-field line. Brendan Rodgers scores. Tony Wolters scores." , "Ian Desmond lines out sharply to center fielder Jason Heyward.", "Ian Desmond hits a grand slam (9) to right center field. Charlie Blackmon scores. Trevor Story scores. David Dahl scores.", "Ian Desmond homers (12) on a fly ball to center field. Daniel Murphy scores.")
df <- data.frame(text, stringsAsFactors=FALSE)
df %>%
filter(str_detect(text, "scores|grand slam|home")) %>%
count()
- 我已经查看了 stackoverflow 提供的“解决方案”,但找不到符合我需要的解决方案。
- 我想计算文本向量的所有行中所有出现的“分数”、“大满贯”和“家” 。
- 我更喜欢 dplyr 解决方案;但是,我对其他方式持开放态度。
- 对于结果,我只想要计数。在提供的输入中,要计算的单词\短语出现了九次。
解决方案
你算作"homers"
匹配"home"
吗?
您可以str_count
通过将单词粘贴为一个模式来使用。
library(stringr)
words <- c('home', 'grand slam', 'scores')
str_count(df$text, str_c(words, collapse = '|'))
#[1] 3 0 4 2
这将计算text
图案 ( str_c(words, collapse = '|')
) 出现的次数。要获得总数,我们可以sum
他们。
sum(str_count(df$text, str_c(words, collapse = '|')))
#[1] 9
"homers"
如果您想以与您不匹配的方式编写模式,"home"
可以在模式 ( ) 周围使用单词边界\\b
。
str_count(df$text, str_c('\\b', words, '\\b', collapse = '|'))
#[1] 3 0 4 1
谁会sum
给你计数为8。
推荐阅读
- python - 如何在松弛 API 中对肤色做出反应
- python - 如何检查是否没有以前的输出
- selenium - 使用硒(python)在登录窗口中捕获电子邮件框
- python - Python Traceback - gradientboosting.py 如何修复此类错误
- bash - 如何使用位置替换字母
- sas - PROC SQL:collect_set 或 group_concat 等价物?
- python - 如何在 QFrame 中设置 QDrag 的缩略图位置?
- python - 如何使用伯努利NB?
- java - MySQL 插入查询中提到的 Java Array 元素未插入到表中。而是抛出错误
- node.js - 如何正确管理投票应用程序中的投票?