rmatrixsparse-matrixlogical-operatorscoerce

Converting dgCMatrix to logical matrix


Consider this simple sparse matrix

> (X <- sparseMatrix(c(1, 2, 1), c(1, 1, 2), x = 0:2))
2 x 2 sparse Matrix of class "dgCMatrix"

[1,] 0 2
[2,] 1 .

How can I convert it into a matrix indicating if the corresponding element is non-empty? Here is what I'm doing now, but being 0 does not equal to being "empty", and this approach doesn't differentiate between them.

> (Y <- X != 0)
2 x 2 sparse Matrix of class "lgCMatrix"

[1,] : |
[2,] | .

To clarify, the desired output may only contain TRUE or FALSE but not NA. It can be either a matrix or a sparseMatrix. Even more preferably, it may be a list, in which case each slot corresponds to a column of X. For example, the answer for X should be either

     [,1]  [,2]
[1,] TRUE  TRUE
[2,] TRUE FALSE

or

$`1`
[1] TRUE TRUE

$`2`
[1]  TRUE FALSE

Solution

  • pex <- function(p) {
        dp <- diff(p)
        rep(seq_along(dp), dp)
    }
    
    m = matrix(FALSE, nrow = nrow(X), ncol = ncol(X))
    m[cbind(X@i + 1, pex(X@p))] = TRUE
    m
    #     [,1]  [,2]
    #[1,] TRUE  TRUE
    #[2,] TRUE FALSE
    

    pex is from here.