我想知道如何在tm packge中得到频率权重这个词(tf =文件中的术语/总词数)`
MyMatrix <- DocumentTermMatrix(a, control = list(weight= weightTf))
使用此重量后,它会显示术语的频率而非TF重量,如此
Doc(1) 1 0 0 3 0 0 2
Doc(2) 0 0 0 0 0 0 0
Doc(3) 0 5 0 0 0 0 1
Doc(4) 0 0 0 2 2 0 0
Doc(5) 0 4 0 0 0 0 1
Doc(6) 5 0 0 0 1 0 0
Doc(7) 0 5 0 0 0 0 0
Doc(8) 0 0 0 1 0 0 7
答案 0 :(得分:0)
像MyMatrix / rowSums(MyMatrix)这样的东西可以给你想要的结果。
但是如果一个文档没有术语(DTM的文档全部为零),则上面会产生一行NaN,如下所示(如你的情况)
Doc(1) 0.1111111 0 0 0.5555556 0.1111111 0.2222222 0.0000000
Doc(2) 0.0000000 1 0 0.0000000 0.0000000 0.0000000 0.0000000
Doc(3) NaN NaN NaN NaN NaN NaN NaN
Doc(4) 1.0000000 0 0 0.0000000 0.0000000 0.0000000 0.0000000
Doc(5) 0.0000000 0 0 0.0000000 0.2857143 0.5714286 0.1428571
因此,更好的方法是:
t(apply(myMatrix, 1, function(x) if(sum(x) != 0) x / sum(x) else x))
带有所需的结果:
Doc(1) 0.1111111 0 0 0.5555556 0.1111111 0.2222222 0.0000000
Doc(2) 0.0000000 1 0 0.0000000 0.0000000 0.0000000 0.0000000
Doc(3) 0.0000000 0 0 0.0000000 0.0000000 0.0000000 0.0000000
Doc(4) 1.0000000 0 0 0.0000000 0.0000000 0.0000000 0.0000000
Doc(5) 0.0000000 0 0 0.0000000 0.2857143 0.5714286 0.1428571
答案 1 :(得分:0)
例如
library(tm)
corp <- Corpus(VectorSource(c(doc1="hello world", doc2="hello new world")))
myfun <- WeightFunction(function(m) {
cs <- slam::col_sums(m)
m$v <- m$v/cs[m$j]
return(m)
}, "Term Frequency by Total Document Term Frequency", "termbytot")
dtm <- DocumentTermMatrix(corp, control = list(weighting = myfun))
inspect(dtm)
# <<DocumentTermMatrix (documents: 2, terms: 3)>>
# Non-/sparse entries: 5/1
# Sparsity : 17%
# Maximal term length: 5
#
# Terms
# Docs hello new world
# 1 0.5000000 0.0000000 0.5000000
# 2 0.3333333 0.3333333 0.3333333