如何将稀疏矩阵转换为索引和非零元素值的矩阵 [英] How to convert a sparse matrix into a matrix of index and value of non-zero element

查看:127
本文介绍了如何将稀疏矩阵转换为索引和非零元素值的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用sparseMatrixspMatrix根据非零元素的索引和值构造稀疏矩阵.是否有任何函数将稀疏矩阵转换回所有非零元素的索引和值?例如

We can construct a sparse matrix from an index and value of non-zero element with the sparseMatrix or spMatrix. Is there any function convert a sparse matrix back to an index and value of all non-zero element? For example

i <- c(1,3,5); j <- c(1,3,4); x <- 1:3
A <- sparseMatrix(i, j, x = x)

B <- sparseToVector(A)
## test case:
identical(B,cbind(i,j,x))

是否有任何功能与sparseToVector相似?

Is there any function do a similar job as sparseToVector?

推荐答案

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

,您可以轻松地将其传递给as.data.frameas.matrix:

which you can easily pass to as.data.frame or as.matrix:

sparseToVector <- function(x)as.matrix(summary(x))
B <- sparseToVector(A)
## test case:
identical(B,cbind(i,j,x))
# [1] TRUE

这篇关于如何将稀疏矩阵转换为索引和非零元素值的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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