将矩阵转换为三列data.frame

时间:2021-12-23 04:28:33

I've got matrix:

我有矩阵:

     var1 var2
row1   1   2
row2   3   4

Want to convert it to data.frame:

想要将其转换为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?

最好的方法是什么?

2 个解决方案

#1


15  

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")))

#2


0  

Here's a solution for the tidyverse using tidyr.

这是使用tidyr的tidyverse的解决方案。

library(tidyverse)

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

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

output

#1


15  

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")))

#2


0  

Here's a solution for the tidyverse using tidyr.

这是使用tidyr的tidyverse的解决方案。

library(tidyverse)

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

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

output