如何在 R 中重组 table

How do I restructure a table in R

我有一个table如下。

 A   B   C
14.29   20.06   20.04
19.10   20.64   26.23
19.09   18.00   22.74
16.25   19.56   22.04
15.09   19.47   23.37
16.61   19.07   25.02
19.63   18.38   23.27

但是我想旋转 table 就像这样。

group    time
A    15.5
A    16.5
A    12.3
A    15.6
B    14.2
B    13.5
B    11.2
C    11.5
C    11.2
C    11.8

我提到了 reshape() 函数,但我感觉它可能是不适合这项工作的工具,因为我遇到了这个错误:

> x.long <- reshape(x, varying = 2:3, direction = "long")
Error in guess(varying) : 
  failed to guess time-varying variables from their names
> help(reshape)
> x.long <- reshape(x, varying = 1:3, direction = "long")
Error in guess(varying) : 
  failed to guess time-varying variables from their names
> x.long <- reshape(x, varying = 0:2, direction = "long")
Error in guess(varying) : 
  failed to guess time-varying variables from their names
> x.long <- reshape(x, varying = 1, direction = "long")
Error in guess(varying) : 
  failed to guess time-varying variables from their names
> x.long <- reshape(x, varying = 1:7, direction = "long")
Error in guess(varying) : 
  failed to guess time-varying variables from their names
> x.long <- reshape(x, direction = "long")
Error in reshape(x, direction = "long") : 
  no 'reshapeWide' attribute, must specify 'varying'
> x.long <- reshape(x, direction = "wide")
Error in `[.data.frame`(data, , timevar) : undefined columns selected
> 

我们可以使用 stack 来自 base R

setNames(stack(df1)[2:1], c("group", "time"))

或使用 reshape2

中的 melt
library(reshape2)
melt(df1, variable.name = "group", value.name = "time")