将 dgCMatrix 转换为逻辑矩阵

Converting dgCMatrix to logical 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 .

如何将其转换为表示对应元素是否为非空的矩阵?这是我现在正在做的,但是 0 不等于 "empty",并且这种方法不区分它们。

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

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

澄清一下,所需的输出可能只包含 TRUEFALSE 而不是 NA。它可以是 matrixsparseMatrix。甚至更优选地,它可以是list,在这种情况下每个槽位对应一列X。例如,X 的答案应该是

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

$`1`
[1] TRUE TRUE

$`2`
[1]  TRUE FALSE
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 来自 here.

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