简体   繁体   中英

Convert from n x m matrix to long matrix in R

Note: This is not a graph question.

I have an nxm 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 nxm matrix and not the other way around. Am I missing something obvious? How can I do this conversion?

Thank you!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM