术语频率表到tm R包中的DocumentTermMatrix

时间:2015-10-17 15:36:01

标签: r text-mining tm word-frequency

我在R中使用tm包进行一些文本挖掘。我有一个术语频率矩阵,其中每一行都是一个文档,每一列都是一个单词,每个单元格都是单词的频率。我试图将其转换为DocumentTermTermMatrix对象。我似乎无法找到一个处理它的功能。看起来源通常是文件。

我已经尝试了as.DocumentTermTermMatrix(),但它要求参数“加权”,并给出以下错误:

  

.TermDocumentMatrix(t(x),加权)出错:
        参数“加权”缺失,没有默认值

这是一个简单的可重现示例的代码

docs = matrix(sample(1:10, 50, replace=T), byrow = TRUE, ncol = 5, nrow=10) 
rownames(docs) = paste0("doc", 1:10)
colnames(docs) = c("grad", "school", "is", "sleep", "deprivation")

所以我需要将矩阵文档强制转换为DocumentTermMatrix

1 个答案:

答案 0 :(得分:1)

使用您的代码示例,您可以使用以下内容:

docs = matrix(sample(1:10, 50, replace=T), byrow = TRUE, ncol = 5, nrow=10) 
rownames(docs) = paste0("doc", 1:10)
colnames(docs) = c("grad", "school", "is", "sleep", "deprivation")

dtm <- as.DocumentTermMatrix(docs, weighting = weightTfIdf)

如果您阅读帮助DocumentTermMatrix,您会在参数

下看到以下内容
  

加权:能够处理TermDocumentMatrix的加权函数。对于术语频率,它默认为weightTf   权重。 tm软件包附带的可用加权函数   是weightTf,weightTfIdf,weightBin和weightSMART。

根据您的需要,您必须指定与文档术语矩阵一起使用的权重公式。或者自己创建一个。