在R中合并两个大小不同的dgCMatrix稀疏矩阵 [英] Merge two dgCMatrix sparse matrices of different size in R

查看:234
本文介绍了在R中合并两个大小不同的dgCMatrix稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在R中合并两个具有不同大小(分别为行和列)的正规类dgCMatrix的大型(约500k列和行)稀疏矩阵?

How can I merge two large (around 500k columns and rows) sparse matrices of formal class dgCMatrix with different sizes (both columns and rows wise) in R?

简化示例:我有一个完整的6x6矩阵

Simplyfied example: I have a full 6x6 matrix

1 2 3 4 5 6
1 0 0 0 0 0 0
2 0 0 0 0 0 0
3 0 0 0 0 0 0
4 0 0 0 0 0 0
5 0 0 0 0 0 0
6 0 0 0 0 0 0

现在我要合并另一个不同大小的矩阵:

Now I want to merge a second matrix of different size:

3 4 5 6
1 0 1 0 0 
3 0 0 1 0 
4 1 0 0 0 

结果应为:

1 2 3 4 5 6
1 0 0 0 1 0 0
2 0 0 0 0 0 0
3 0 0 0 0 1 0
4 1 0 0 0 0 0
5 0 0 0 0 0 0
6 0 0 0 0 0 0

我尝试了cbindX并合并,但是两者都不起作用:

I tried cbindX and merge but both didn't work as either:

只能使用矩阵和data.frames

only matrices and data.frames can be used

不能将类"* structure(" dgCMatrix,package =" Matrix)"强制转换为data.frame.

cannot coerce class "*structure("dgCMatrix", package = "Matrix")" to a data.frame.

但是,我无法按照此处的建议将矩阵更改为sparse=FALSE矩阵类

However, I could not change my matrix to sparse=FALSE matrix class as suggested here in this post or to a data.frame, as in this case R cannot handle the matrix size on my machine anymore.

任何帮助将不胜感激.谢谢!

Any help would be highly appreciated. Thanks!

推荐答案

一种策略是将矩阵转换回相同的大小,然后添加它们.

One strategy would be to convert the matrices back to the same size and then add them.

A <- sparseMatrix(8, 8, x = 1)
B <- sparseMatrix(c(1,3,5), c(3,6,3), x = c(1,4,1))

您可以使用summary(B)访问矩阵B的索引,然后像使用R中的常规子集操作一样,仅使用sparseMatrix(i,j,x,dims)重新创建矩阵即可.

You can access the indices of matrix B with summary(B) and then just recreate the matrix with sparseMatrix(i,j,x,dims) like you would a normal subsetting operation in R:

> summary(B)
5 x 6 sparse Matrix of class "dgCMatrix", with 3 entries 
  i j x
1 1 3 1
2 5 3 1
3 3 6 4

B <- sparseMatrix(i = summary(B)$i, j = summary(B)$j, x = summary(B)$x, dims = dim(A))

然后您可以添加矩阵:

A = A + B

这篇关于在R中合并两个大小不同的dgCMatrix稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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