给定一个矩阵 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
给定一个矩阵 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
尝试:which(M==1, arr.ind=TRUE)
row col
[1,] 1 1
[2,] 3 2
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