每期频率 - R TM DocumentTermMatrix

时间:2013-01-20 17:03:38

标签: r tm term-document-matrix

我对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

2 个答案:

答案 0 :(得分:7)

它似乎是数据的稀疏矩阵组织。看起来频率位于“v”列表中,您可以通过在“条款”属性中查找术语的位置来获得该频率。为什么不提供dput(head(results, 30)),以便您的代码(和您的SO观众)可以使用?在使用包装中的示例后,我怀疑您确实需要以下内容:

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

答案 1 :(得分: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))
相关问题