3

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
nalzok
  • 14,965
  • 21
  • 72
  • 139

2 Answers2

3
Y <- as(X, "lgCMatrix") #should be more efficient than X != 0
Y@x[] <- TRUE #set all values to TRUE
as.matrix(Y)
#     [,1]  [,2]
#[1,] TRUE  TRUE
#[2,] TRUE FALSE
Roland
  • 127,288
  • 10
  • 191
  • 288
2
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.

d.b
  • 32,245
  • 6
  • 36
  • 77