如何解决Grepl 字符串组和所有使用 R 的计数频率
我有一列 50k 行推文,名为 text 来自 csv 文件(推文由句子、短语等组成)。我正在尝试计算该列中几个单词的频率。有没有比我在下面做的更简单的方法?
# Reading my file
tweets <- read.csv('coffee.csv',header=TRUE)
# Doing a grepl per word (This is hard because I need to look for many words one by one)
coffee <- grepl("coffee",text$tweets,ignore.case=TRUE)
mugs <- grepl("mugs",ignore.case=TRUE)
# Calculate the % of times among all tweets (This is hard because I need to calculate one by one)
sum(coffee) / nrow(text)
sum(starbucks) / nrow(text)
预期输出(假设我有超过 2 个单词)
Word Freq
coffee 50
mugs 40
cup 64
pen 12
解决方法
您可以创建要计算频率/百分比的词的向量,并使用 sapply
来计算它们。
words <- c('coffee','mugs')
data.frame(words,t(sapply(paste0('\\b',words,'\\b'),function(x) {
tmp <- grepl(x,tweets$text)
c(perc = mean(tmp) * 100,Freq = sum(tmp))
})),row.names = NULL) -> result
result
# words perc Freq
#1 coffee 33.33333 1
#2 mugs 66.66667 2
sapply
类似于 for
循环,因为它遍历 words
中定义的每个单词。 grepl
返回 TRUE
/FALSE
值,指示单词是否出现在存储在 tweets$text
中的 tmp
中。我们使用 sum
来计算频率,我们使用 mean
来计算百分比。还为单词添加了单词边界 (\\b
),以便它们在 text
中完全匹配,因此 'coffee'
与 'coffees'
等不匹配。
数据
tweets <- data.frame(text = c('This is text with coffee in it with lot of mugs','This has only mugs','This has nothing'))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。