Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a built-in function in either slam package or Matrix package to convert a sparse matrix in simple triplet matrix form (from slam package) to a sparse matrix in dgTMatrix/dgCMatrix form (from Matrix package) ?

And is there a built-in way to access non-zero entries from simple triplet matrix ?

I'm working in R

like image 910
GorillaInR Avatar asked Nov 15 '13 15:11

GorillaInR


2 Answers

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.

like image 171
GorillaInR Avatar answered Oct 29 '22 16:10

GorillaInR


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) {

  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
      ),
    dimnames = dimnames(simple_triplet_matrix_sparse)
  )

}
like image 39
user3465707 Avatar answered Oct 29 '22 17:10

user3465707