您好,我有一个来自 tidytext::unnest_tokens()
和 count(category, word, name = "count")
的管道。看起来就像这个例子。
owl <- tibble(category = c(0, 1, 2, -1, 0, 1, 2),
word = c(rep("hello", 3), rep("world", 4)),
count = sample(1:100, 7))
我想获得带有附加列的小标题,该列给出了该单词出现的类别数,即每次该单词出现的类别数相同。
我尝试了以下主要有效的代码。结果就是我想要的。
owl %>% mutate(sum_t = sapply(1:nrow(.), function(x) {filter(., word == .$word[[x]]) %>% nrow()}))
但是,看到我的数据有数十万行,这需要相当长的时间。有没有更有效的方法来实现这一目标?
最佳答案
我们可以使用add_count
:
library(dplyr)
owl %>%
add_count(word)
输出:
category word count n
<dbl> <chr> <int> <int>
1 0 hello 98 3
2 1 hello 30 3
3 2 hello 37 3
4 -1 world 22 4
5 0 world 80 4
6 1 world 18 4
7 2 world 19 4
关于r - 如何计算每个文档每行一个标记中单词/标记的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71814291/