【问题标题】:Grepl group of strings and count frequency of all using RGrepl 字符串组和所有使用 R 的计数频率
【发布时间】:2021-02-06 04:06:01
【问题描述】:

我有一列来自 csv 文件的名为 text 的 50k 行推文(推文由句子、短语等组成)。我正在尝试计算该列中几个单词的频率。有没有比我在下面做的更简单的方法?

# 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", text$tweets, 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

【问题讨论】:

    标签: r count grepl


    【解决方案1】:

    您可以创建要计算频率/百分比的单词向量,并使用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 值,指示该单词是否存在于存储在 tmp 中的 tweets$text 中。计算频率我们使用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'))
    

    【讨论】:

    • 嗨罗纳克!至于获取数据,我有 50k 条推文,我认为将它放在向量 c 中是行不通的。如何从 Tweets.csv 导入它? (列名:文本)
    • 您不必将数据一一放入向量中。您已经拥有数据tweets &lt;- read.csv('coffee.csv', header=TRUE)。您需要将要计算频率的单词放入向量中。 words &lt;- c('coffee', 'mugs', 'cup', 'pen')
    • 谢谢你的作品!你能解释一下 data.frame 中的代码行吗?比如 sapply 的作用和 tmp 是什么?
    • 我在答案中添加了一些代码解释。希望对您有所帮助。
    • 抱歉最后一个问题,如果我有喜欢 2 个单词但我想将它们算作一个喜欢:“冰咖啡”怎么办?我必须制作一个 gsub 吗?
    猜你喜欢
    • 2011-12-11
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多