如何将稀疏矩阵转换为索引矩阵和非零元素值

Jul*_*ian 14 r sparse-matrix

我们可以从与所述非零元素的索引,并且值构造一个稀疏矩阵sparseMatrixspMatrix.有没有函数将稀疏矩阵转换回索引和所有非零元素的值?例如

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))
Run Code Online (Sandbox Code Playgroud)

是否有任何功能做类似的工作sparseToVector

cbe*_*ica 9

您的矩阵A采用稀疏压缩格式(类dgCMatrix).您可以将其强制转换为非压缩稀疏格式

A.nc <- as (A, "dgTMatrix")
Run Code Online (Sandbox Code Playgroud)

或者,您可以giveCsparse = TRUEsparseMatrix通话中指定.

的三重形式dgTMatrix基本上包含你在插槽寻找一切i,jx,只是ij索引与基于0的偏移来完成:

> 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
Run Code Online (Sandbox Code Playgroud)


flo*_*del 8

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
Run Code Online (Sandbox Code Playgroud)

您可以轻松传递给as.data.frameas.matrix:


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