2013-05-08 141 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