R:从长到长重塑 - 结果搞砸了

时间:2016-05-02 20:40:27

标签: r dataframe reshape

我想重新调整我的数据,但是我搞砸了一些事情:

data <- as.data.frame(matrix(c(1:5,0,0,0,5,1,0,0,0,5,0,2,6,2,1,7,6,8,2,4,5),5,5))
colnames(data) <- c("id", "x1.a", "x3.a", "y1.a", "y3.a")
print(data)

#   id x1.a x3.a y1.a y3.a
# 1  1    0    0    2    6
# 2  2    0    0    6    8
# 3  3    0    0    2    2
# 4  4    5    5    1    4
# 5  5    1    0    7    5

reshaped <- reshape(data,
                    varying = 2:5,
                    v.names = c("x.a","y.a"),
                    times = c(1,3),
                    timevar = "time",
                    idvar = "id",
                    direction = "long")
reshaped <- reshaped[with(reshaped,order(id,time)),]

# Result:
#     id time x.a y.a
# 1.1  1    1   0   0
# 1.3  1    3   2   6
# 2.1  2    1   0   0
# 2.3  2    3   6   8
# 3.1  3    1   0   0
# 3.3  3    3   2   2
# 4.1  4    1   5   5
# 4.3  4    3   1   4
# 5.1  5    1   1   0
# 5.3  5    3   7   5

正如您在上面所看到的,重塑后,x1.ay1.a被组合在一起(x.a),x3.ay3.a被分组在一起(y.a)。我想要的是x1.ax3.a组合在一起(y1.ay3.a相同),如下所示:

#     id time x.a y.a
# 1.1  1    1   0   2
# 1.3  1    3   0   6
# 2.1  2    1   0   6
# 2.3  2    3   0   8
# 3.1  3    1   0   2
# 3.3  3    3   0   2
# 4.1  4    1   5   1
# 4.3  4    3   5   4
# 5.1  5    1   1   7
# 5.3  5    3   0   5

我做错了什么?感谢。

2 个答案:

答案 0 :(得分:1)

帮助文件说

  

请注意,变量的顺序类似于x.1,y.1,x.2,y.2。

所以这会奏效:

reshape(data, varying = c(2,4,3,5), 
     v.names = c("x.a","y.a"),
     times = c(1,3),
     timevar = "time",
     idvar = "id",
     direction = "long")

您必须对列重新排序,以便每个时间段的变量都相邻。

在这个例子中,R在没有v.names和times参数的情况下做得相当不错,所以

reshape(data,
    varying = c(2,4,3,5),
    timevar = "time",
    idvar = "id",
    direction = "long")

产生几乎相同的结果,唯一的区别是变量名称x.a和y.a变为xa和ya。

答案 1 :(得分:0)

以下是来自melt的{​​{1}}的替代方案,可能需要多个data.table measure

patterns

如果我们希望'time'列为1,3

library(data.table)
dM <- melt(setDT(data), measure = patterns("^x", "^y"), 
        value.name = c("x.a", "y.a"), variable.name = "time")[order(id)]
dM
#    id time x.a y.a
# 1:  1    1   0   2
# 2:  1    2   0   6
# 3:  2    1   0   6
# 4:  2    2   0   8
# 5:  3    1   0   2
# 6:  3    2   0   2
# 7:  4    1   5   1
# 8:  4    2   5   4
# 9:  5    1   1   7
#10:  5    2   0   5