【问题标题】:How to remove columns with all elements zero in a sparse Matrix?如何删除稀疏矩阵中所有元素为零的列?
【发布时间】:2012-10-26 18:19:20
【问题描述】:

例如,M 是一个稀疏矩阵,track_list 是矩阵的列名。

library(Matrix)
M <- Matrix(0,nrow = 3,ncol = 4)
M[1,2] = 1
M[2,3] = 1
M[3,2] = 1 
track_list = c('a','b','c','d')
colnames(M) = track_list

col_tmp <- M@p[-1] - M@p[-length(M@p)]
M <- M[,col_tmp!=0]
track_list = track_list[col_tmp!=0]

结果将是:

> M
3 x 2 sparse Matrix of class "dgCMatrix"
     b c
[1,] 1 .
[2,] . 1
[3,] 1 .

但是,设计很丑。那么该怎么做呢?

谢谢。

【问题讨论】:

    标签: r matrix sparse-matrix


    【解决方案1】:

    使用summary() 获取包含非零条目的列索引的sparseSummary 可能最直接。

    library(Matrix)
    M <- Matrix(c(0,0,0,1,0,0,0,1,1,1,0,0), nc=4)
    M[,unique(summary(M)$j)]
    # 3 x 3 sparse Matrix of class "dgCMatrix"
    #           
    # [1,] 1 . 1
    # [2,] . 1 .
    # [3,] . 1 .
    
    ## To see how it works, compare M and summary(M)
    M 
    # 3 x 4 sparse Matrix of class "dgCMatrix"
    #             
    # [1,] . 1 . 1
    # [2,] . . 1 .
    # [3,] . . 1 .
    
    summary(M)
    # 3 x 4 sparse Matrix of class "dgCMatrix", with 4 entries 
    #   i j x
    # 1 1 2 1
    # 2 2 3 1
    # 3 3 3 1
    # 4 1 4 1
    

    【讨论】:

      【解决方案2】:

      试试这个:

      M <- matrix(0,nrow = 3,ncol = 4)
      M[1,2] = M[2,3] = M[3,2] = 1
      M = M[,colSums(M != 0) != 0]
      

      如果您有兴趣使用Matrix 包,您可以完全按照上述方式进行操作——只需将matrix(...) 更改为Matrix(...)。这些点是零值,不用担心:

      M = Matrix(0,nrow = 3,ncol = 4)
      M
      # 3 x 4 sparse Matrix of class "dgCMatrix"
      # [1,] . . . .
      # [2,] . . . .
      # [3,] . . . .
      
      M[1,1]
      # [1] 0
      

      实际上,Matrix 包似乎对 sparse 矩阵(一些非零元素的矩阵)进行了优化。因此,它通过点显示零,以更好地表示矩阵的稀疏程度。

      【讨论】:

      • 但是,我怎样才能得到所有元素的列的索引都是零
      • 对于由c(-1, 0, 1) 组成的列不会失败吗?
      • 现在看起来不错。也可能比我的效率更高,虽然我没有检查过。
      • 看起来我的更快(至少是许多可能的)大型矩阵(基于执行M &lt;- as(spMatrix(nrow=1e6, ncol=1e6, i=1:3, j=1:3, x=c(1,2,3)), "dgCMatrix"),然后使用system.time() 比较我们的方法。)
      • @JoshO'Brien 有趣!我已经赞成你的方法。
      猜你喜欢
      • 2015-09-20
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 2017-06-05
      • 1970-01-01
      • 2021-06-24
      相关资源
      最近更新 更多