reshape2和宽(推算)时间变量

时间:2016-11-26 21:10:59

标签: r reshape2 melt

我知道基础R中的reshape可以转换为长格式,其中时间来自存根变量名称AB,例如:

wide = data.frame(A.2010 = c('a', 'b', 'c'),
                  A.2011 = c('f', 'g', 'd'),
                  B.2010 = c('A', 'B', 'C'),
                  B.2011 = c('G', 'G', 'H'),
                  z = runif(3),
                  x = runif(3))

wide
#  A.2010 A.2011 B.2010 B.2011         z          x
#1      a      f      A      G 0.3626823 0.67212468
#2      b      g      B      G 0.3726911 0.09663248
#3      c      d      C      H 0.9807237 0.31259394

变为:

reshape(wide, direction = 'long', sep = '.',
        varying = c('A.2010', 'A.2011', 'B.2010', 'B.2011'))
#               z          x time A B id
#1.2010 0.3626823 0.67212468 2010 a A  1
#2.2010 0.3726911 0.09663248 2010 b B  2
#3.2010 0.9807237 0.31259394 2010 c C  3
#1.2011 0.3626823 0.67212468 2011 f G  1
#2.2011 0.3726911 0.09663248 2011 g G  2
#3.2011 0.9807237 0.31259394 2011 d H  3

我可以使用reshape2::melt完成相同的操作吗?

1 个答案:

答案 0 :(得分:2)

基础r中的reshape似乎是执行此操作的最佳工具,因为melt包中reshape2函数中没有类似的功能。但是,您可以使用patterns中的melt.data.table函数实现类似的功能:

library(reshape2)
library(data.table)

wide = data.table(wide)

long = melt(wide, id.vars = c("z", "x"), measure = patterns("^A", "^B"),
            value.name = c("A", "B"), variable.name = "time")

> long
           z         x time A B
1: 0.3421681 0.8432707    1 a A
2: 0.1243282 0.5096108    1 b B
3: 0.3650165 0.1441660    1 c C
4: 0.3421681 0.8432707    2 f G
5: 0.1243282 0.5096108    2 g G
6: 0.3650165 0.1441660    2 d H

请注意melt可识别变化的“时间”,并对其进行正确分组,但不会根据需要使用2010和2011。解决方法是手动重新编码级别,这应该是微不足道的。

levels(long$time) = c("2010", "2011")

> long
           z         x time A B
1: 0.3421681 0.8432707 2010 a A
2: 0.1243282 0.5096108 2010 b B
3: 0.3650165 0.1441660 2010 c C
4: 0.3421681 0.8432707 2011 f G
5: 0.1243282 0.5096108 2011 g G
6: 0.3650165 0.1441660 2011 d H

我希望这有帮助!