14

Note: This is not a graph question.

I have an n x m matrix:

> m = matrix(1:6,2,3)
> m
  a  b  c
d 1  2  3
e 4  5  6

I would like to convert this to a long matrix:

> m.l
a d 1
a e 4
b d 2
b e 5
c d 3
c e 6

Obviously nested for loops would work but I know there are a lot of nice tools for reshaping matrixes in R. So far, I have only found literature on converting from long or wide matrixes to an n x m matrix and not the other way around. Am I missing something obvious? How can I do this conversion?

Thank you!

user3030872
  • 367
  • 1
  • 6
  • 14

1 Answers1

22

If you need a single column matrix

 matrix(m, dimnames=list(t(outer(colnames(m), rownames(m), FUN=paste)), NULL))
 #    [,1]
 #a d    1
 #a e    4
 #b d    2
 #b e    5
 #c d    3
 #c e    6

For a data.frame output, you can use melt from reshape2

 library(reshape2)
 melt(m)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Check out `acast(data, formula)` and `dcast(data, formula)` for the reverse process. Great for storing and retrieving matrices in a database... – sdittmar Aug 24 '20 at 14:40
  • @akrun, what if I have missing values (blank) in some of my starting columns? I get ```Error in matrix(sunrise2016, dimnames = list(t(outer(colnames(sunrise2016), : length of 'dimnames' [1] not equal to array extent``` I'm assuming that is why I get this error. – Johnny5ish Feb 05 '21 at 18:09