Search code examples
rmatrixsparse-matrix

R sparse matrix stores zeros after simple arithmetic (Matrix library)


I have the following [10 x 10] sparse matrix:

library(Matrix)
m = as(diag(10), 'sparseMatrix')
m
10 x 10 sparse Matrix of class "dgCMatrix"
[1,] 1 . . . . . . . . .
[2,] . 1 . . . . . . . .
[3,] . . 1 . . . . . . .
[4,] . . . 1 . . . . . .
[5,] . . . . 1 . . . . .
[6,] . . . . . 1 . . . .
[7,] . . . . . . 1 . . .
[8,] . . . . . . . 1 . .
[9,] . . . . . . . . 1 .
[10,] . . . . . . . . . 1

If I do simple arithmetic on this, it now stores all of the zeros.

M = m + 1 - 1
M
10 x 10 Matrix of class "dgeMatrix"
       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    0    0    0    0    0    0    0    0     0
 [2,]    0    1    0    0    0    0    0    0    0     0
 [3,]    0    0    1    0    0    0    0    0    0     0
 [4,]    0    0    0    1    0    0    0    0    0     0
 [5,]    0    0    0    0    1    0    0    0    0     0
 [6,]    0    0    0    0    0    1    0    0    0     0
 [7,]    0    0    0    0    0    0    1    0    0     0
 [8,]    0    0    0    0    0    0    0    1    0     0
 [9,]    0    0    0    0    0    0    0    0    1     0
[10,]    0    0    0    0    0    0    0    0    0     1

I know that I can make this new matrix sparse, but is there any way to make R do this automatically?

M = as(M, 'sparseMatrix')

Solution

  • It calculates m+1-1 as (m+1)-1 and m+1 is not sparse so from that point on you don't have a sparse matrix.

    Try m+(1-1).