融化多组measure.vars

时间:2014-02-10 23:43:04

标签: r data.table reshape reshape2

我有一个data.table包含多年的多个变量,即:

> dt <- data.table(id=1:3, A_2011=rnorm(3), A_2012=rnorm(3), 
                           B_2011=rnorm(3), B_2012=rnorm(3), 
                           C_2011=rnorm(3), C_2012=rnorm(3))
> dt
   id     A_2011       A_2012    B_2011     B_2012     C_2011     C_2012
1:  1 -0.8262134  0.832013744 -2.320136  0.1275409 -0.1344309  0.7360329
2:  2  0.9350433  0.279966534 -0.725613  0.2514631  1.0246772 -0.2009985
3:  3  1.1520396 -0.005775964  1.376447 -1.2826486 -0.8941282  0.7513872

我想把这个表格按年份变成变量组,即:

> dtLong <- data.table(id=rep(dt[,id], 2), year=c(rep(2011, 3), rep(2012, 3)), 
                       A=c(dt[,A_2011], dt[,A_2012]), 
                       B=c(dt[,B_2011], dt[,B_2012]), 
                       C=c(dt[,C_2011], dt[,C_2012]))
> dtLong
   id year            A          B          C
1:  1 2011 -0.826213405 -2.3201355 -0.1344309
2:  2 2011  0.935043336 -0.7256130  1.0246772
3:  3 2011  1.152039595  1.3764468 -0.8941282
4:  1 2012  0.832013744  0.1275409  0.7360329
5:  2 2012  0.279966534  0.2514631 -0.2009985
6:  3 2012 -0.005775964 -1.2826486  0.7513872

我可以使用melt.data.frame包中的reshape2轻松地为一组变量执行此操作:

> melt(dt[,list(id, A_2011, A_2012)], measure.vars=c("A_2011", "A_2012"))

但是,对于具有共同“因素”的多个measure.vars,无法实现此目的。

2 个答案:

答案 0 :(得分:15)

您可以使用基础R中的reshape轻松完成此操作

reshape(dt, varying = 2:7, sep = "_", direction = 'long')

这将为您提供以下输出

      id time          A            B            C
1.2011  1 2011 -0.1602428  0.428154271  0.384892382
2.2011  2 2011  1.4493949  0.178833067  2.404267878
3.2011  3 2011 -0.1952697  1.072979813 -0.653812311
1.2012  1 2012  1.7151334  0.007261567  1.521799983
2.2012  2 2012  1.0866426  0.060728118 -1.158503305
3.2012  3 2012  1.0584738 -0.508854175 -0.008505982

答案 1 :(得分:2)

来自?熔体样品:

melt(DT, id=1:2, measure=patterns("^f_", "^d_"), value.factor=TRUE)