从 R 中的 dtm 按每个文档的频率提取顶级特征

Extract top features by frequency per document from a dtm in R

我有一个 dtm,想从文档词条矩阵中提取每个文档的前 5 个词频。

我有一个 dtm 使用 tm 包构建

  Terms                     
Docs aaaa aac abrt abused accept accepted
1 0 0 0 0 0 0 
2 0 0 0 0 0 0
3 0 0 0 0 0 0
4 0 0 0 0 0 0
5 0 0 0 0 0 0
6 0 0 0 0 0 0

所需的输出应为以下形式:

Id   
1   Term1 Term2 Term3 Term4 Term5
2   Term1 Term2 Term3 Term4 Term5
and so on for all the documents.

我已经尝试了 Whosebug 和其他来源提供的所有解决方案 像 Make dataframe of top N frequent terms for multiple corpora using tm package in R(转换为 tdm 并试图带入输出形式但没有工作)和其他但注意似乎工作。

使用全达达:

library(quanteda)
txt <- c("hello world world fizz", "foo bar bar buzz")
dfm <- dfm(txt)
topfeatures(dfm, n = 2, groups = seq_len(ndoc(dfm)))
# $`1`
# world hello 
# 2     1 
# 
# $`2`
# bar foo 
# 2   1 

您还可以在 DocumentTermMatrixdfm 之间进行转换。

或者使用经典的tm

library(tm)
packageVersion("tm")
# [1] ‘0.7.1’
txt <- c(doc1="hello world world", doc2="foo bar bar fizz buzz")
dtm <- DocumentTermMatrix(Corpus(VectorSource(txt)))
n <- 5
(top <- findMostFreqTerms(dtm, n = n))
# $doc1
# world hello 
# 2     1 
# 
# $doc2
# bar buzz fizz  foo 
# 2    1    1    1 
do.call(rbind, lapply(top, function(x) { x <- names(x);length(x)<-n;x }))
# [,1]    [,2]    [,3]   [,4]  [,5]
# doc1 "world" "hello" NA     NA    NA  
# doc2 "bar"   "buzz"  "fizz" "foo" NA 

findMostFreqTermstm version 0.7-1.

可用