如何在R中将正则矩阵转换为稀疏矩阵? [英] How to convert a regular matrix to a sparse matrix in R?

查看:753
本文介绍了如何在R中将正则矩阵转换为稀疏矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个200K行x 27K列矩阵,我想将其转换为稀疏矩阵.我已经尝试过这样做,但是遇到了细分错误:

I have a 200K row x 27K column matrix and I'd like to convert it to a sparse matrix. 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'

有更好的方法吗?

推荐答案

首先,如果as(my_regular, "sparseMatrix")提供段错误-请报告给Matrix程序包维护者(可以在此处找到

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

这篇关于如何在R中将正则矩阵转换为稀疏矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆