Convert matrix to three column data.frame

Aleksandro M Granda picture Aleksandro M Granda · Nov 10, 2014 · Viewed 15.9k times · Source

I've got matrix:

     var1 var2
row1   1   2
row2   3   4

Want to convert it to data.frame:

rows vars values
row1 var1   1
row1 var2   2
row2 var1   3
row2 var2   4

What is the best way to do it?

Answer

akrun picture akrun · Nov 10, 2014

You can use melt

library(reshape2)
setNames(melt(m1), c('rows', 'vars', 'values'))
#  rows vars values
#1 row1 var1      1
#2 row2 var1      3
#3 row1 var2      2
#4 row2 var2      4

Or

data.frame(rows=rownames(m1)[row(m1)], vars=colnames(m1)[col(m1)],
                      values=c(m1))
#   rows vars values
#1 row1 var1      1
#2 row2 var1      3
#3 row1 var2      2
#4 row2 var2      4

Or

 as.data.frame(as.table(m1))
 #    Var1 Var2 Freq
 #1 row1 var1    1
 #2 row2 var1    3
 #3 row1 var2    2
 #4 row2 var2    4

data

m1 <- structure(c(1L, 3L, 2L, 4L), .Dim = c(2L, 2L), .Dimnames = list(
c("row1", "row2"), c("var1", "var2")))