Search code examples
rsparse-matrix

how to get the none zero indexes of a sparseMatrix?


Given a 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 .

how can I extract a list of indexed wich point to none zero values at that cell? In this case for example a data.frame like this:

  x y
1 1 1
2 3 2

Solution

  • Try: which(M==1, arr.ind=TRUE)

         row col
    [1,]   1   1
    [2,]   3   2