2013-04-06 48 views
11

我們可以使用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)) 

有沒有什麼功能可以做類似sparseToVector的工作嗎?

回答

5
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


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

使用whicharr.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 
7

你的矩陣A是在稀疏的壓縮格式(類dgCMatrix)。您可以通過

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

或者強制其非壓縮格式的稀疏,你可以在電話sparseMatrix指定giveCsparse = TRUE

dgTMatrix的三重形式基本上包含了所有你在插槽ij尋找,並x,只是ij索引與基於0的偏移進行:

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

> cbind (i = [email protected] + 1, j = [email protected] + 1, x = [email protected]) 
    i j x 
[1,] 1 1 1 
[2,] 3 3 2 
[3,] 5 4 3 
> all (cbind (i = [email protected] + 1, j = [email protected] + 1, x = [email protected]) == cbind (i, j, x)) 
[1] TRUE 
+0

@ flodel:恩......好吧......說服了。 – cbeleites 2013-04-06 13:01:44

+0

你不是指'giveCsparse = FALSE'? – 2015-01-15 09:48:15