Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 587
nalzok Avatar asked Nov 23 '25 02:11

nalzok


1 Answers

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
like image 80
Roland Avatar answered Nov 25 '25 21:11

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!