Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating sparse matrix from a list of sparse vectors

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?

like image 342
DAF Avatar asked Dec 10 '22 03:12

DAF


1 Answers

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
like image 59
Josh O'Brien Avatar answered Jan 30 '23 23:01

Josh O'Brien