在矩阵列表中:保留每个矩阵中的非零部分

In a list of matrices: keep the non-zero section in each matrix

我有一个维度不同的矩阵列表,每个矩阵都有一个全零行或一列或一个全零列和一个全零行。我相信应该有一种有效的单线方法 trim 将它们降到非零,但我还没有找到它。

dput(mt)
list(A = structure(c(1, 7, 9, 0, 3, 4, 1, 0, 0, 0, 0, 0), dim = 4:3), 
    B = structure(c(1, 0, 3, 0, 8, 0, 2, 0), dim = c(2L, 4L)), 
    C = structure(c(1, 3, 8, 2, 0, 0, 0, 0), dim = c(4L, 2L)))

我的预期结果是这样的

    $A
     [,1] [,2]
[1,]    1    3
[2,]    7    4
[3,]    9    1

$B
     [,1] [,2] [,3] [,4]
[1,]    1    3    8    2

$C
     [,1]
[1,]    1
[2,]    3
[3,]    8
[4,]    2

我们可以创建 row/column 索引,其中行全为 0 或列全为 0,在逻辑矩阵上使用 rowSums/colSums,然后为 row/column 索引创建逻辑向量

lapply(mt, function(x)
    {
      m1 <- x == 0
      x[!(rowSums(m1)== ncol(m1)), 
      !(colSums(m1) == nrow(m1)),drop = FALSE]
     }
 )

-输出

$A
     [,1] [,2]
[1,]    1    3
[2,]    7    4
[3,]    9    1

$B
     [,1] [,2] [,3] [,4]
[1,]    1    3    8    2

$C
     [,1]
[1,]    1
[2,]    3
[3,]    8
[4,]    2