use*_*594 3 r matrix sparse-matrix
例如,M是稀疏矩阵,track_list是矩阵的colnames.
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]
Run Code Online (Sandbox Code Playgroud)
结果将是:
> M
3 x 2 sparse Matrix of class "dgCMatrix"
b c
[1,] 1 .
[2,] . 1
[3,] 1 .
Run Code Online (Sandbox Code Playgroud)
但是,设计很难看.那怎么办?
谢谢 .
使用它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
Run Code Online (Sandbox Code Playgroud)