R包矩阵:获取稀疏矩阵每行/列的非零条目数

R package Matrix: get number of non-zero entries per rows / columns of a sparse matrix

我有一个大的稀疏矩阵("dgCMatrix",维度 5e+5 x 1e+6)。我需要计算每一列有多少个非零值,并制作一个只有 1 个非零条目的列名列表。

我的代码适用于小矩阵,但对于我需要处理的实际矩阵来说计算量太大了。

library(Matrix)
set.seed(0)
mat <- Matrix(matrix(rbinom(200, 1, 0.10), ncol = 20))
colnames(mat) <- letters[1:20]

entries <- colnames(mat[, nrow(mat) - colSums(mat == 0) == 1])

非常欢迎任何建议!

I have a large sparse matrix ("dgCMatrix")

姑且称它为dgCMat

I need to count for each column how many non-zero values there are

xx <- diff(dgCMat@p)

and make a list of column names with only 1 non-zero entry

colnames(dgCMat)[xx == 1]

总结

nnz:非零数

对于 "dgCMatrix" dgCMat:

## nnz per column
diff(dgCMat@p)

## nnz per row
tabulate(dgCMat@i + 1)

对于 "dgRMatrix" dgRMat:

## nnz per column
tabulate(dgRMat@j + 1)

## nnz per row
diff(dgRMat@p)

对于 "dgTMatrix" dgTMat:

## nnz per column
tabulate(dgTMat@j + 1)

## nnz per row
tabulate(dgTMat@i + 1)

发布此答案时我没有阅读您的原始代码。所以我不知道你被 mat == 0 的使用困住了。直到后来,我才在您的回答中添加了 mat == 0mat != 0 之间的区别。

您使用 mat != 0 的解决方法很好地利用了软件包的功能。同一行代码也适用于其他稀疏矩阵 类。我的直接进入内部存储,因此不同的 类.

需要不同的版本

使用以下方法产生类似的结果: 请注意提供的评论:

## `mat != 0` returns a "lgCMatrix" which is sparse
## don't try `mat == 0` as that is dense, simply because there are too many zeros
entries <- colnames(mat)[colSums(mat != 0) == 1]