鉴于Matrix M:
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
答案 0 :(得分:2)
尝试:which(M==1, arr.ind=TRUE)
row col
[1,] 1 1
[2,] 3 2
答案 1 :(得分: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
## ..@ i : int [1:2] 0 2
## ..@ p : int [1:4] 0 1 2 2
## ..@ Dim : int [1:2] 3 3
## ..@ Dimnames:List of 2
## .. ..$ : NULL
## .. ..$ : NULL
## ..@ x : num [1:2] 1 1
## ..@ uplo : chr "L"
## ..@ diag : chr "N"
help("dtCMatrix-class")
help("CsparseMatrix-class")
低级答案:
cols <- rep(1:3,diff(M@p))
rows <- M@i+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