Merge two dgCMatrix sparse matrices of different size in R

后端 未结 1 1772
甜味超标
甜味超标 2021-01-14 05:55

How can I merge two large (around 500k columns and rows) sparse matrices of formal class dgCMatrix with different sizes (both columns and rows wise) in R?

相关标签:
1条回答
  • 2021-01-14 06:31

    One strategy would be to convert the matrices back to the same size and then add them.

    A <- sparseMatrix(8, 8, x = 1)
    B <- sparseMatrix(c(1,3,5), c(3,6,3), x = c(1,4,1))
    

    You can access the indices of matrix B with summary(B) and then just recreate the matrix with sparseMatrix(i,j,x,dims) like you would a normal subsetting operation in R:

    > summary(B)
    5 x 6 sparse Matrix of class "dgCMatrix", with 3 entries 
      i j x
    1 1 3 1
    2 5 3 1
    3 3 6 4
    
    B <- sparseMatrix(i = summary(B)$i, j = summary(B)$j, x = summary(B)$x, dims = dim(A))
    

    Then you can just add the matrices:

    A = A + B
    
    0 讨论(0)
提交回复
热议问题