0

I would like to use R to convert a dense (or sparse) matrix into a compressed 3 column dataframe similar to the data presentation shown below (taken from a python question here: Convert N by N Dataframe to 3 Column Dataframe).

I am able to use sparseMatrix package to convert a 3-column format into a sparse matrix, but how does one reverse this conversion?

print df1
>>> print df1
       a  b  c  d  e
index               
a      0  1  4  5  7
b      1  0  1  1  1
c      2  2  0  2  2
d      3  3  3  0  3
e      4  4  4  4  0

>>> print rel_df
   fld1 fld2  value
0     a    b      1
1     a    c      4
2     a    d      5
3     a    e      7
4     b    a      1
5     b    c      1
6     b    d      1
7     b    e      1
8     c    a      2
9     c    b      2
10    c    d      2
11    c    e      2
12    d    a      3
13    d    b      3
14    d    c      3
15    d    e      3
16    e    a      4
17    e    b      4
18    e    c      4
19    e    d      4
Community
  • 1
  • 1
Matt
  • 73
  • 9
  • 3
    Having a "sparseMatrix" and not creating an intermediate dense "matrix", see `summary(df1)` – alexis_laz Apr 28 '16 at 14:42
  • @alexis_laz Consider to post as an answer. I think that is the one. – akrun Apr 28 '16 at 14:45
  • 1
    @42- && akrun : perhaps [this](http://stackoverflow.com/questions/15849641/how-to-convert-a-sparse-matrix-into-a-matrix-of-index-and-value-of-non-zero-elem) is a more suited duplicate? – alexis_laz Apr 28 '16 at 14:49
  • Thanks! What an incredibly simply solution summary(df1) is. – Matt Apr 28 '16 at 15:18
  • I think of `as.data.frame.table` as the "original `melt`". It works to construct an i-j-val structure, although in the case of a sparse matrix from the Matrix package you may need to first coerce to a dense form via `(as.matrix(A))` – IRTFM Apr 28 '16 at 16:55

0 Answers0