I want to reshape my data from wide to long, but I'm messing something up:
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
As you can see above, after the reshaping, x1.a
and y1.a
are grouped together (in x.a
), and x3.a
and y3.a
are grouped together (in y.a
). What I want is for x1.a
and x3.a
to be grouped together (and the same for y1.a
and y3.a
), like so:
# 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
What am I doing wrong? Thanks.