简体   繁体   English

如何在R中将规则矩阵转换为稀疏矩阵?

[英]How to convert a regular matrix to a sparse matrix in R?

I have a 200K row x 27K column matrix and I'd like to convert it to a sparse matrix. 我有一个200K行x 27K列矩阵,我想将其转换为稀疏矩阵。 I've tried doing this, but I get a segmentation fault: 我已经尝试过这样做,但是遇到了细分错误:

> dim(my_regular)
[1] 196501  26791

> my_sparse <- as(my_regular, "sparseMatrix")

 *** caught segfault ***
address 0x2b9e3e10e000, cause 'memory not mapped'

Is there a better way? 有没有更好的办法?

This is definitely not ideal, but the only way I could get the conversion to happen was to break up the matrix in groups of 50K rows and then use rbind to combine them: 这绝对不是理想的,但是我可以进行转换的唯一方法是将矩阵分成5万行,然后使用rbind组合它们:

my_sparse_1 <- Matrix::Matrix(my_regular[1:50000,], sparse = TRUE)
my_sparse_2 <- Matrix::Matrix(my_regular[50001:100000,], sparse = TRUE)
# etc.
my_sparse <- rbind(my_sparse_1, my_sparse_2, etc.)

I won't accept my answer, in case anyone has a better suggestion 如果有人有更好的建议,我不会接受我的回答

First of all if as(my_regular, "sparseMatrix") gives segfault - please report to Matrix package maintainer (can be found here https://cran.r-project.org/web/packages/Matrix/index.html ). 首先,如果as(my_regular, "sparseMatrix")给出段错误-请向Matrix软件包维护者报告(可在此处找到https://cran.r-project.org/web/packages/Matrix/index.html )。

As a workaround you can use something like this: 作为解决方法,您可以使用以下方法:

library(Matrix)
nc = 50
nr = 100
sparsity = 0.9
m = sample(c(0, 1), size = nr * nc, replace = TRUE, prob = c(sparsity, 1 - sparsity))
m = matrix(m, nr, nc)

# normal way of coercing dense to sparse
spm1 = as(m, "CsparseMatrix")

# get indices of non-zero elements
ind_nnz = which(m != 0)

# construct zero-based indices of row and column
i = (ind_nnz - 1L) %% nr
j = as.integer((ind_nnz - 1L) / nr)
# get non-zero values
x = m[ind_nnz]

spm2 = sparseMatrix(i = i, j = j, x = x, dims = c(nr, nc), index1 = FALSE)

identical(spm1, spm2)
# TRUE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM