2013-04-06 7 views
11

Wir können eine dünn besetzte Matrix aus einem Index und einem Wert eines Nicht-Null-Elements mit sparseMatrix oder spMatrix konstruieren. Gibt es irgendeine Funktion, die eine dünn besetzte Matrix zurück in einen Index und einen Wert aller Nicht-Null-Elemente umwandelt? Zum BeispielWie man eine dünn besetzte Matrix in eine Matrix aus Index und Wert eines Nicht-Null-Elements umwandelt

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)) 

Gibt es eine Funktion, um eine ähnliche Arbeit wie sparseToVector tun?

Antwort

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 

die Sie können leicht zu as.data.frame oder as.matrix gehen:


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

Verwendung which mit 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 
7

Ihre Matrix A ist in der spärlichen komprimierten Format (Klasse dgCMatrix). Sie können es in den nicht komprimierten spärlichen Format von

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

coerce Oder Sie giveCsparse = TRUE im sparseMatrix Aufruf angegeben haben könnte.

Die Triplett-Form dgTMatrix grundsätzlich alle für Sie suchen enthält in Schlitze i, j und x, nur i und j Indizierung mit 0 basierten Offsets getan:

> 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: Naja ... OK ... überredet. – cbeleites

+0

meinst du nicht 'giveCsparse = FALSE'? –

Verwandte Themen