R: Reshape from wide to long, can't get order right

萝らか妹 提交于 2019-12-11 12:23:38

问题


I reshaped my data from wide to long, but I can't get the order right:

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

I want the values in x1.a and x3.a to be grouped by id, like so:

#     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

Can anyone help? Thanks.


回答1:


You mean you just want to sort the data frame? Cause that's pretty easy:

> 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


来源:https://stackoverflow.com/questions/36985260/r-reshape-from-wide-to-long-cant-get-order-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!