r - Convert matrix to three column data.frame -
i've got matrix:
var1 var2 row1 1 2 row2 3 4
want convert data.frame:
rows vars values row1 var1 1 row1 var2 2 row2 var1 3 row2 var2 4
what best way it?
you can utilize 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")))
r matrix data.frame reshape
No comments:
Post a Comment