I would like to convert a sparse matrix into a data frame of the type (row,column, value). I have found questions such as http://r.789695.n4.nabble.com/Converting-sparse-matrix-to-data-frame-in-Matrix-package-td2332012.html 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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With