Search code examples
rsparse-matrix

How to convert a sparse matrix into a matrix of index and value of non-zero element


We can construct a sparse matrix from an index and value of non-zero element with the sparseMatrix or spMatrix. Is there any function convert a sparse matrix back to an index and value of all non-zero element? For example

i <- c(1,3,5); j <- c(1,3,4); x <- 1:3
A <- sparseMatrix(i, j, x = x)

B <- sparseToVector(A)
## test case:
identical(B,cbind(i,j,x))

Is there any function do a similar job as sparseToVector?


Solution

  • summary(A)
    # 5 x 4 sparse Matrix of class "dgCMatrix", with 3 entries 
    #   i j x
    # 1 1 1 1
    # 2 3 3 2
    # 3 5 4 3
    

    which you can easily pass to as.data.frame or as.matrix:


    sparseToVector <- function(x)as.matrix(summary(x))
    B <- sparseToVector(A)
    ## test case:
    identical(B,cbind(i,j,x))
    # [1] TRUE