Convert from nxm matrix to long matrix in R

Note. This is not a question of the graph.

I have a nxm matrix:

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

I would like to convert this to a long matrix:

 > ml ad 1 ae 4 bd 2 be 5 cd 3 ce 6 

Obviously, nested for loops will work, but I know that there are many good tools for converting matrices to R. So far I have only found literature on converting from long or wide matrices to nxm matrix, and not the other way. something missing? How can I do this conversion?

Thanks!

+6
source share
1 answer

If you need one column matrix

  matrix(m, dimnames=list(t(outer(colnames(m), rownames(m), FUN=paste)), NULL)) # [,1] #ad 1 #ae 4 #bd 2 #be 5 #cd 3 #ce 6 

To output data.frame you can use melt from reshape2

  library(reshape2) melt(m) 
+7
source

Source: https://habr.com/ru/post/987639/


All Articles