首页 > 解决方案 > 需要计算 R # 列中预先指定的单词

问题描述

我需要计算以下单词\短语在一列中出现的次数:

  1. 大满贯
  2. 分数

这是行形式的输入:

[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()
  1. 我已经查看了 stackoverflow 提供的“解决方案”,但找不到符合我需要的解决方案。
  2. 我想计算文本向量的所有行中所有出现的“分数”、“大满贯”和“家” 。
  3. 我更喜欢 dplyr 解决方案;但是,我对其他方式持开放态度。
  4. 对于结果,我只想要计数。在提供的输入中,要计算的单词\短语出现了九次。

标签: rdplyr

解决方案


你算作"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。


推荐阅读