How to store Sparsity and Maximum term length of a Term document matrix from tm

霸气de小男生 提交于 2019-12-02 12:14:28

This will return the stats you need. Your question did not specify what format you desired, so here I have used a named list. (This could easily be returned as a data.frame.)

I took this from the tm package source code, file Matrix.R, where the print method for TermDocumentMatrix objects is defined.

getTDMstats <- function(x) {
    # where x is a TermDocumentMatrix
    list(sparsity = ifelse(!prod(dim(x)), 100, round((1 - length(x$v)/prod(dim(x))) * 100)) / 100,
         maxtermlength = max(nchar(Terms(x), type = "chars"), 0), 
         weightingLong = attr(x, "weighting")[1], 
         weightingShort = attr(x, "weighting")[2], 
         nonsparse = length(x$v), 
         sparse = prod(dim(x)) - length(x$v))
}
data(crude)
tdm2 <- TermDocumentMatrix(crude)
tdm2
## <<TermDocumentMatrix (terms: 1266, documents: 20)>>
## Non-/sparse entries: 2255/23065
## Sparsity           : 91%
## Maximal term length: 17
## Weighting          : term frequency (tf)
getTDMstats(tdm2)
## $sparsity
## [1] 0.91
## 
## $maxtermlength
## [1] 17
## 
## $weightingLong
## [1] "term frequency"
## 
## $weightingShort
## [1] "tf"
## 
## $nonsparse
## [1] 2255
## 
## $sparse
## [1] 23065
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!