11

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

GorillaInR
  • 675
  • 2
  • 7
  • 19
  • 3
    Your not likely to get much help with that kind of question. A reproducible example of your situation will help a lot, and some code showing what you have tried so far, at least. – Chargaff Nov 15 '13 at 15:43
  • 6
    This question doesn't need a reproducible example. A simple triplet matrix is a simple triplet matrix no matter what data it contains. I'm asking this question to find if there's a built-in function in either package to support conversion between the two. I'm not asking for ad hoc code which I could do myself. – GorillaInR Nov 15 '13 at 15:53
  • No, there doesn't seem to be a built-in function to convert between sparse matrices generated by the Matrix and slam packages. – Chargaff Nov 15 '13 at 16:12

2 Answers2

23

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.

GorillaInR
  • 675
  • 2
  • 7
  • 19
  • 3
    I do not agree. With a reproducible example, a yes/no question like your's will get more informative answers and they will contain practical examples. Your chances to see more than one answer will also greatly improve. – Chargaff Nov 18 '13 at 19:30
3

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

}
Gabriel J. Odom
  • 336
  • 2
  • 9
  • The `slam::` package does not store indices as factors (as of 2020), so the calls to `as.numeric()` should not be necessary. Otherwise, this is a fine function to have. – Gabriel J. Odom Feb 25 '20 at 21:43