0

Below is an excerpt from my data:

data <- as.data.frame(matrix(c(rep(1,3),rep(2,3),rep(1:3,2),rep(0:2,4)),6,4))
colnames(data) <- c("id", "rater", "x", "y")
print(data)

#   id rater x y
# 1  1     1 0 0
# 2  1     2 1 1
# 3  1     3 2 2
# 4  2     1 0 0
# 5  2     2 1 1
# 6  2     3 2 2

I reshaped it from long to wide:

reshape(data, timevar = "rater", idvar = "id", direction = "wide")

# Result:
#   id x.1 y.1 x.2 y.2 x.3 y.3
# 1  1   0   0   1   1   2   2
# 4  2   0   0   1   1   2   2

But instead of the default order (order by timevar, i.e., x.1, y.1, x.2, y.2, x.3, y.3), I want the order to be the same as the original order the columns appeared before reshaping (i.e., all x, then all y; x.1, x.2, x.3, y.1, y.2, y.3).

I could do it manually but I have 100+ columns to reshape. I tried ?reshape but couldn't find anything.

Thanks!

  • 1
    Do it post-hoc. This isn't the same as doing it manually. If the columns are named as you show then `result = result[sort(names(result))]` should work to reorder the column. – Gregor Thomas May 02 '16 at 00:30

1 Answers1

1

This can be achieved by using dcast from data.table which can take multiple value.var

library(data.table)
dcast(setDT(data), id~rater, value.var=c("x", "y"), sep=".")
#   id x.1 x.2 x.3 y.1 y.2 y.3
#1:  1   0   1   2   0   1   2
#2:  2   0   1   2   0   1   2
akrun
  • 874,273
  • 37
  • 540
  • 662