每项术语的频率 - R TM文档-词矩阵

4

我是一名 R 语言的新手,对于 DocumentTermMatrixs 这个概念还不太理解。我使用了 TM 包创建了一个 DocumentTermMatrix,其中包含了词项频率以及相应的词项,但我不知道如何访问它们。

理想情况下,我希望能够:

    Term  # 
    "the" 200 
    "is"  400 
    "a"   200 

目前我的代码是:

    library(tm)
    common.words <- c("amp","@RT","I","http","https", stopwords("english"), "you")
    x <- Corpus(VectorSource(results)) 
    x <- tm_map(x, stripWhitespace) 
    x <- tm_map(x, removeNumbers) 
    x <- tm_map(x, removePunctuation) 
    x <- tm_map(x, stripWhitespace)

    dtm <- DocumentTermMatrix(x)
    for(i in 1:length(common.words)) {
    dtm <- dtm[,!colnames(dtm)%in%c(common.words[i])]
    }

这是 str(dtm) 的输出结果。

   List of 6
   $ i       : int [1:9769] 1 1 1 1 1 1 1 1 2 2 ...
   $ j       : int [1:9769] 1596 1684 1858 2112 2175 2490 2714 2814 873 961 ...
   $ v       : num [1:9769] 1 1 2 1 1 2 1 1 1 1 ...
   $ nrow    : int 1477
   $ ncol    : int 3201
   $ dimnames:List of 2
   ..$ Docs : chr [1:1477] "1" "2" "3" "4" ...
   ..$ Terms: chr [1:3201] "\u0093\u0085a" "aardvark" "aaron" "abbie" ...
    - attr(*, "class")= chr [1:2] "DocumentTermMatrix" "simple_triplet_matrix"
    - attr(*, "Weighting")= chr [1:2] "term frequency" "tf"

谢谢,
-A

1
你可以尝试使用 inspect(dtm) - agstudy
2个回答

7

这似乎是数据的稀疏矩阵结构。看起来频率在“v”列表中,你可以通过查找术语属性中你的术语的位置来获得它。为什么不提供dput(head(results, 30)),这样你的代码(以及你的 SO 受众)就会有可用的内容?在使用软件包示例时,我怀疑你实际上想要的是以下内容:

tdm <- TermDocumentMatrix(x)
z <- inspect( tdm[ c("the", "is", "a"), dimnames(tdm)$Docs] )
rowSums(z)

3

我有同样的问题,并找到了一种我认为更简单的方法:

num <- 10 # Show this many top frequent terms

tdm[findFreqTerms(tdm)[1:num],] %>%
      as.matrix() %>%
      rowSums()

在栏中打印文本比较棘手(我相信有比这更好的方法):

terms <- findFreqTerms(tdm)[1:num]
tdm[terms,] %>%
      as.matrix() %>%
      rowSums()  %>% 
      data.frame(Term = terms, Frequency = .) %>%  
      arrange(desc(Frequency))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接