Converting a dgCMatrix to Data Frame

I would like to convert a sparse matrix into a data frame of the type (row,column, value). I have found questions such as that in the question start with row,column,value and create a sparse matrix. I want the inverse, and I cannot use the as.matrix function, because the matrix is too large. Here is a small example.

r = c(1,2,2,3,3)
c = c(4,1,2,3,5)
v = c(1,2,1,3,1)

a = sparseMatrix(i=r,j=c,x=v) 

3 x 5 sparse Matrix of class "dgCMatrix"

[1,] . . . 1 .
[2,] 2 1 . . .
[3,] . . 3 . 1

Can I get a data.frame

  r c v
1 1 4 1
2 2 1 2
3 2 2 1
4 3 3 3
5 3 5 1

Thank you

2

1 Answer

You can use

b = as.data.frame(summary(a))
#   i j x
# 1 2 1 2
# 2 2 2 1
# 3 3 3 3
# 4 1 4 1
# 5 3 5 1

If you need the same order as in your example, you can use

b = b[order(b$i),]
#   i j x
# 4 1 4 1
# 1 2 1 2
# 2 2 2 1
# 3 3 3 3
# 5 3 5 1

Another alternative, though not quite as neat, is to use

b = as(a, "dgTMatrix")
cbind.data.frame(r = b@i + 1, c = b@j + 1, x = b@x)
6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest