2013-05-08 41 views
0

給定矩陣M:如何獲得sparseMatrix的零零索引?

M <- Matrix(c(1,0,0,0,0,1,0,0,0), nrow=3, sparse=T) 

M 
3 x 3 sparse Matrix of class "dtCMatrix" 

[1,] 1 . . 
[2,] . . . 
[3,] . 1 . 

我怎麼能零個值,在該單元格中提取索引至極點的無法比擬的名單? 在這種情況下,例如像這樣的data.frame:

x y 
1 1 1 
2 3 2 
+1

可以添加哪個包'矩陣()'從何而來? – Chase 2013-05-08 12:51:32

回答

2

嘗試:which(M==1, arr.ind=TRUE)

 row col 
[1,] 1 1 
[2,] 3 2 
1
library("Matrix") 
M <- Matrix(c(1,0,0,0,0,1,0,0,0), nrow=3, sparse=T) 

往裏:

str(M) 
## Formal class 'dtCMatrix' [package "Matrix"] with 7 slots 
## [email protected] i  : int [1:2] 0 2 
## [email protected] p  : int [1:4] 0 1 2 2 
## [email protected] Dim  : int [1:2] 3 3 
## [email protected] Dimnames:List of 2 
## .. ..$ : NULL 
## .. ..$ : NULL 
## [email protected] x  : num [1:2] 1 1 
## [email protected] uplo : chr "L" 
## [email protected] diag : chr "N" 

help("dtCMatrix-class") 
help("CsparseMatrix-class") 

的低級別答案:

cols <- rep(1:3,diff([email protected])) 
rows <- [email protected]+1 
cbind(x=rows,y=cols) 

但是,它看起來像上面給出確實採取稀疏的優勢which()答案,所以這是一個更好的答案:

t1 <- new("dtTMatrix", x= c(3,7), i= 0:1, j=3:2, 
      Dim= as.integer(c(1e6,1e6))) 
which(t1>0,arr.ind=TRUE) 
##  [,1] [,2] 
## [1,] 1 4 
## [2,] 2 3