r - 融化多组 measure.vars

标签 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 却无法实现这一点有一个共同的“因素”。

最佳答案

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

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

关于r - 融化多组 measure.vars,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21690235/

相关文章:

reshape::recast 不会使用 fill=NA 求和

python - Numpy 优化 reshape : 2D array to 3D

r - 在 r 中动画 ggmap

r - 错误打破for循环: conditional try statement?

r - 来自不同数据框的样本

python - 使用shape或pivot_table reshape pandas数据框(堆叠每行)

R - 在 x 轴和 y 轴上使用具有不同变量的 corrplot

r - 创建正则表达式以从行值中删除字符串和字符

r - 将向量附加到 data.table 作为单独的新列,向量回收单个值

r - 为什么在 `j` 中评估比在 `$` 中评估 `data.table` 更快?