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?
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
m1 <- structure(c(1L, 3L, 2L, 4L), .Dim = c(2L, 2L), .Dimnames = list(
c("row1", "row2"), c("var1", "var2")))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With