问题
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