从类"simple_triplet_matrix"转换为类"matrix"

Cpt*_*emo 6 r matrix tm

我正在尝试转换使用TermDocumentMatrix()该tm包创建的以下简单三元组矩阵

A term-document matrix (317443 terms, 86960 documents)

Non-/sparse entries: 18472230/27586371050
Sparsity           : 100%
Maximal term length: 653 
Weighting          : term frequency (tf)
Run Code Online (Sandbox Code Playgroud)

班级

[1] "TermDocumentMatrix"    "simple_triplet_matrix" 
Run Code Online (Sandbox Code Playgroud)

到密集的矩阵.

但

dense <- as.matrix(tdm)
Run Code Online (Sandbox Code Playgroud)

生成错误

Error in vector(typeof(x$v), nr * nc) : vector size cannot be NA
In addition: Warning message:
In nr * nc : NAs produced by integer overflow
Run Code Online (Sandbox Code Playgroud)

我无法真正理解错误和警告信息.尝试使用的小数据集复制错误

library(tm)
data("crude")
tdm <- TermDocumentMatrix(crude)
as.matrix(tdm)
Run Code Online (Sandbox Code Playgroud)

不会产生同样的问题.我从这个答案中看到,通过slam包解决了类似的问题(即使问题是关于求和操作而不是转换为密集矩阵).我浏览了slam文档,但是我找不到任何特定的函数来将类simple_triplet_matrix的对象转换为类的对象matrix.

ags*_*udy 2

您会收到错误,因为正如所评论的那样,您达到了整数限制,这是正常的,因为您有大量文档。这会重现该错误:

as.integer(.Machine$integer.max+1)
[1] NA
Warning message:
NAs introduced by coercion 
Run Code Online (Sandbox Code Playgroud)

vector使用整数作为参数的函数失败,因为它的第二个参数是 NA。

一种解决方案是重新定义as.matrix.simple_triplet_matrix而不调用vector. 例如:

as.matrix.simple_triplet_matrix <- 
function (x, ...) 
{
  nr <- x$nrow
  nc <- x$ncol
  ## old line: y <- matrix(vector(typeof(x$v), nr * nc), nr, nc)
  y <- matrix(0, nr, nc)  ## 
  y[cbind(x$i, x$j)] <- x$v
  dimnames(y) <- x$dimnames
  y
}
Run Code Online (Sandbox Code Playgroud)

但我不确定强制转换为稀疏矩阵(100%)这样的矩阵是个好主意。

编辑

saparseMatrix一种想法是从包中使用Matrix。这是我比较每个强制生成的对象的示例。通过使用,你至少获得了 10 倍的系数(我认为对于非常稀疏的矩阵,你会获得更多)sparseMatrix。此外,稀疏矩阵支持加法和乘法。

require(tm)
data("crude")
dtm <- TermDocumentMatrix(crude,
                          control = list(weighting = weightTfIdf,
                                         stopwords = TRUE))
library(Matrix)
Dense <- sparseMatrix(dtm$i,dtm$j,x=dtm$v)
dense <- as.matrix(dtm)
## check sizes 
floor(as.numeric(object.size(dense)/object.size(Dense)))
## addistion and multiplication are supported
Dense+Dense
Dense*Dense
Run Code Online (Sandbox Code Playgroud)