david-cortes / MatrixExtra

(R) Efficient methods and operators for the sparse matrix classes in 'Matrix' (esp. CSR format or "RsparseMatrix")
https://cran.r-project.org/package=MatrixExtra
GNU General Public License v3.0
20 stars 3 forks source link

rbind() cannot be used with do.call() #9

Closed rcastelo closed 4 months ago

rcastelo commented 4 months ago

Hi,

I want to iterate through the rows of a large sparse matrix, and found the subsetting-row operator of the MatrixExtra package very handy because it provides a sparseVector object for each row. The result of that iteration is again a sparseVector for each row, which I would like to row-bind back into a sparseMatrix. The problem is that, I would do that with a do.call(), but it chokes when more than two elements in the argument list are given:

library(Matrix)
library(MatrixExtra)

row_ix <- c(1, 1, 2, 3)
col_ix <- c(1, 3, 3, 2)
values <- c(1, 2, 3, 4)
X <- Matrix::sparseMatrix(
     i=row_ix, j=col_ix, x=values,
     index1=TRUE, repr="T"
 )
do.call(rbind, list(X[1, ], X[2, ]))
Sparse CSR matrix (class 'dgRMatrix')
Dimensions: 2 x 3
(3 entries, 50.00% full)
do.call(rbind, list(X[1, ], X[2, ], X[3, ]))
Error in rbind2(..1) : no method for coercing this S4 class to a v
david-cortes commented 4 months ago

You can use MatrixExtra::rbind_csr:

do.call(rbind_csr, list(X[1, ], X[2, ], X[3, ]))
Sparse CSR matrix (class 'dgRMatrix')
Dimensions: 3 x 3
(4 entries, 44.44% full)

As for the lack of rbind with sparseVector objects, perhaps you could bring that up with the Matrix authors.