convert simple triplet matrix(slam) to sparse matrix(Matrix) in R

百般思念 提交于 2019-12-05 02:25:37

Actually, there is a built-in way:

simple_triplet_matrix_sparse <-  sparseMatrix(i=simple_triplet_matrix_sparse$i, j=simple_triplet_matrix_sparse$j, x=simple_triplet_matrix_sparse$v,
           dims=c(simple_triplet_matrix_sparse$nrow, simple_triplet_matrix_sparse$ncol))

From my own experience, this trick saved me tons of time and miseries, and computer crashing doing large-scale text mining using tm package. This question doesn't really need a reproducible example. A simple triplet matrix is a simple triplet matrix no matter what data it contains. This question is merely asking if there's a built-in function in either package to support conversion between the two.

slight modification. sparseMatrix takes integers as inputs, whereas slam takes i, j, as factors and v can be anything

as.sparseMatrix <- function(simple_triplet_matrix_sparse) {
  retval <-  sparseMatrix(i=as.numeric(simple_triplet_matrix_sparse$i),
                          j=as.numeric(simple_triplet_matrix_sparse$j),
                          x=as.numeric(as.character(simple_triplet_matrix_sparse$v)),
                          dims=c(simple_triplet_matrix_sparse$nrow, 
                                 simple_triplet_matrix_sparse$ncol),
                          dimnames = dimnames(simple_triplet_matrix_sparse),
                          giveCsparse = TRUE)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!