R:从长到长重塑,无法获得正确的订单

时间:2016-05-02 14:45:04

标签: r dataframe reshape

我将数据从长到长重新整理,但我无法获得正确的订单:

data <- as.data.frame(matrix(c(rep(1:5),0,0,0,5,1,0,0,0,5,0),5,3))
colnames(data) <- c("id", "x1.a", "x3.a")
print(data)

#   id x1.a x3.a
# 1  1    0    0
# 2  2    0    0
# 3  3    0    0
# 4  4    5    5
# 5  5    1    0

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

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

我希望x1.ax3.a中的值按id分组,如下所示:

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

有人可以帮忙吗?感谢。

1 个答案:

答案 0 :(得分:1)

您的意思是您只想对数据框进行排序?因为这很简单:

> reshaped[with(reshaped,order(id,time)),]
    id time x.a
1.1  1    1   0
1.3  1    3   0
2.1  2    1   0
2.3  2    3   0
3.1  3    1   0
3.3  3    3   0
4.1  4    1   5
4.3  4    3   5
5.1  5    1   1
5.3  5    3   0