How to convert a sparse matrix into a matrix of index and value of non-zero element

被刻印的时光 ゝ 提交于 2019-11-28 11:58:44
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

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

Your matrix A is in the sparse compressed Format (class dgCMatrix). You can coerce it into the non-compressed sparse format by

A.nc <- as (A, "dgTMatrix")

Or, you could have specified giveCsparse = TRUE in the sparseMatrix call.

The triplet form of dgTMatrix basically contains all you're looking for in slots i, j, and x, just i and j indexing is done with 0-based offsets:

> str (A.nc)
Formal class 'dgTMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:3] 0 2 4
  ..@ j       : int [1:3] 0 2 3
  ..@ Dim     : int [1:2] 5 4
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ x       : num [1:3] 1 2 3
  ..@ factors : list()

> cbind (i = A.nc@i + 1, j = A.nc@j + 1, x = A.nc@x)
     i j x
[1,] 1 1 1
[2,] 3 3 2
[3,] 5 4 3
> all (cbind (i = A.nc@i + 1, j = A.nc@j + 1, x = A.nc@x) == cbind (i, j, x))
[1] TRUE

Use which with arr.ind:

idx <- which(A != 0, arr.ind=TRUE)
cbind(idx, A[idx])
#      [,1] [,2] [,3]
# [1,]    1    1    1
# [2,]    3    3    2
# [3,]    5    4    3
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!