Search code examples
rmatrixsparse-matrix

Row standardize a Sparse Matrix


I have the following sparse matrix;-

library(Matrix)
 a <- sparseMatrix(i = c(1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 5),
                   j = c(1, 2, 2, 3, 2, 3, 4, 5, 3, 1, 5), x = 1)

I want to divide the rows by their row sums so that this matrix becomes the following sparse matrix:-

b <- sparseMatrix(i = c(1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 5),
                  j = c(1, 2, 2, 3, 2, 3, 4, 5, 3, 1, 5),
                  x = c(0.5, 0.5, 0.5, 0.5, 0.25, 0.25, 0.25, 0.25, 1, 0.5, 0.5))

How can I row standardize a sparse matrix in R


Solution

  • You can divide a by rowwise sum.

    b <- a/rowSums(a)
    b
    #5 x 5 sparse Matrix of class "dgCMatrix"
                                
    #[1,] 0.5 0.50 .    .    .   
    #[2,] .   0.50 0.50 .    .   
    #[3,] .   0.25 0.25 0.25 0.25
    #[4,] .   .    1.00 .    .   
    #[5,] 0.5 .    .    .    0.50