如何重构R中的表

时间:2016-10-09 05:29:33

标签: r data.table reshape

我有一张表格如下。

 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

但我想旋转表格就好了。

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
> 

1 个答案:

答案 0 :(得分:0)

我们可以使用stack

中的base R
setNames(stack(df1)[2:1], c("group", "time"))

或使用melt

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