Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert matrix to three column data.frame [duplicate]

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?

like image 520
Aleksandro M Granda Avatar asked Nov 10 '14 07:11

Aleksandro M Granda


2 Answers

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")))
like image 151
akrun Avatar answered Nov 12 '22 19:11

akrun


Here's a solution for the tidyverse using tidyr.

library(tidyverse)

input <- 
  tribble(
    ~rows,   ~var1,  ~var2,
    "row1",  1,      2,
    "row2",  3,      4
  )

output <-
  input %>%
  gather(vars,count,-rows) %>%
  arrange(rows)

output
like image 2
jimbo Avatar answered Nov 12 '22 20:11

jimbo