Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 550
HowYaDoing Avatar asked Nov 26 '18 17:11

HowYaDoing


1 Answers

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)
like image 139
dww Avatar answered Sep 21 '22 20:09

dww