I have a list of sparse vectors (in R). I need to convert this list to a sparse matrix. Doing it via a for-loop takes a long time.
sm<-spMatrix(length(tc2),n.col)
for(i in 1:length(tc2)){
sm[i,]<-(tc2[i])[[1]];
}
Is there a better way?
Here is a two step solution:
Use lapply()
and as(..., "sparseMatrix")
to convert the list of sparseVectors to a list of one column sparseMatrices.
Use do.call()
and cBind()
to combine the sparseMatrices in a single sparseMatrix.
require(Matrix)
# Create a list of sparseVectors
ss <- as(c(0,0,3, 3.2, 0,0,0,-3), "sparseVector")
l <- replicate(3, ss)
# Combine the sparseVectors into a single sparseMatrix
l <- lapply(l, as, "sparseMatrix")
do.call(cBind, l)
# 8 x 3 sparse Matrix of class "dgCMatrix"
#
# [1,] . . .
# [2,] . . .
# [3,] 3.0 3.0 3.0
# [4,] 3.2 3.2 3.2
# [5,] . . .
# [6,] . . .
# [7,] . . .
# [8,] -3.0 -3.0 -3.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With