Search code examples
rmatrixsparse-matrix

Assign "sparse" values to the diagonal of a sparse Matrix in R


I want to assign empty or sparse values into a sparse matrix in R. Specifically I want to remove all values in the diagonal of a sparse matrix from the Matrix package. I am currently only able to assign non-sparse 0's into the diagonal and then remove them with the drop0 function.

Is there a way to assign empty values directly into the diagonal of a sparse matrix?

The following code demonstrates the problem:

    library(Matrix)
    m       <- Diagonal(10) 
    diag(m) <- 0
    m
    drop0(m)

I would like to skip the drop0(m) step. In my real analysis I have off-diagonal values that I want to keep for a network analysis, so I am not really interested in a empty matrix but a way to assign "sparse" or "empty" values into a sparse matrix.


Solution

  • I assume you have indeed a matrix of class ddiMatrix and want to create an empty matrix:

    m1 <- as(m, "generalMatrix")
    m1@i <- integer(0)
    m1@p <- m1@p * 0L
    m1@x <- numeric(0)
    #10 x 10 sparse Matrix of class "dgCMatrix"
    #                         
    # [1,] . . . . . . . . . .
    # [2,] . . . . . . . . . .
    # [3,] . . . . . . . . . .
    # [4,] . . . . . . . . . .
    # [5,] . . . . . . . . . .
    # [6,] . . . . . . . . . .
    # [7,] . . . . . . . . . .
    # [8,] . . . . . . . . . .
    # [9,] . . . . . . . . . .
    #[10,] . . . . . . . . . .
    

    Of course, you could also simply construct a new empty sparse matrix of these dimensions.

    If you have a CsparseMatrix with off-diagonal values, coerce it to a TsparseMatrix and remove all i, j, x values where i == j (or skip the coercion and calculate the correct indices from i and p which I find difficult).

    m1 <- as(m, "generalMatrix")
    
    m2 <- as(m1, "TsparseMatrix")
    
    del <- m2@i == m2@j
    m2@i <- m2@i[!del]
    m2@j <- m2@j[!del]
    m2@x <- m2@x[!del]