我们可以从与所述非零元素的索引,并且值构造一个稀疏矩阵sparseMatrix
或spMatrix
.有没有函数将稀疏矩阵转换回索引和所有非零元素的值?例如
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
?
您的矩阵A
采用稀疏压缩格式(类dgCMatrix
).您可以将其强制转换为非压缩稀疏格式
A.nc <- as (A, "dgTMatrix")
Run Code Online (Sandbox Code Playgroud)
或者,您可以giveCsparse = TRUE
在sparseMatrix
通话中指定.
的三重形式dgTMatrix
基本上包含你在插槽寻找一切i
,j
和x
,只是i
和j
索引与基于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)
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.frame
或as.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)
归档时间: |
|
查看次数: |
6850 次 |
最近记录: |