Search code examples
rmachine-learningsparse-matrix

Subtract ith value of a vector from non zero values of the ith row of a sparse matrix in R


I want to subtract ith value of the vector from non zero values of the ith row of a sparse matrix for e.g.

     [,1] [,2] [,3] [,4]
[1,]    0    0    4    0
[2,]    0    5    0    3
[3,]    1    2    0    0

and here is the vector that i am trying to subtract:

[1] 1 2 3

so what i need in the end is:

     [,1] [,2] [,3] [,4]
[1,]    0    0    3    0
[2,]    0    3    0    1
[3,]   -2   -1    0    0

I have tried this using apply but haven't been able to figure the problem out, it does not return me quite what i want. The dimensions of the matrix are too large and I do not want to use loops. Thanks and regards.


Solution

  • Since subtracting a vector from a matrix is performed column-wise, mat-vec does the necessary subtraction. Since you only want to use this when the original matrix was non-zero (and return 0 for the elements that were originally 0), you could multiply by mat != 0, which is a 1/0 (TRUE/FALSE) matrix stating whether the original element was non-zero.

    (mat - vec) * (mat != 0)
    #      [,1] [,2] [,3] [,4]
    # [1,]    0    0    3    0
    # [2,]    0    3    0    1
    # [3,]   -2   -1    0    0
    

    If you instead wanted to do it for a sparse matrix:

    library(Matrix)
    (mat <- sparseMatrix(i=c(3, 2, 3, 1, 2), j=c(1, 2, 2, 3, 4), x=c(1, 5, 2, 4, 3)))
    # 3 x 4 sparse Matrix of class "dgCMatrix"
    # [1,] . . 4 .
    # [2,] . 5 . 3
    # [3,] 1 2 . .
    vec <- c(1, 2, 3)
    mat@x <- mat@x - vec[mat@i+1]
    mat
    # 3 x 4 sparse Matrix of class "dgCMatrix"              
    # [1,]  .  . 3 .
    # [2,]  .  3 . 1
    # [3,] -2 -1 . .