问题
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:
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
来源:https://stackoverflow.com/questions/36973466/r-reshape-from-long-to-wide-order-of-reshaped-columns-as-original-column-order