例如,M是一个稀疏的Matrix,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 .

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

谢谢 。

最佳答案

使用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

09-25 18:50
查看更多