将长转换为宽时指定列顺序
Specify column order when casting long to wide
我想使用 reshape2 将 table 转换为宽格式。我希望在 vars 上对列进行排序,如下所示:
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
这样投射:
# 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
x 后跟 y,对于每个样本。
现在我正在使用 dcast 并获得以下输出:
dcast(as.data.table(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
但我希望它是x.1, y.1, x.2, y.2
等等
我可以通过重塑(原始)来做到这一点,但是我的数据花费的时间太长了(超过 50 万行,每个 table 需要 15 分钟以上,加上 20+GB 的内存)
reshape(data, idvar = id, timevar = "rater", direction = "wide")
谢谢!
一个选项是提取列名的数字部分,order
out <- dcast(as.data.table(data), id~rater, value.var=c("x", "y"), sep=".")
setcolorder(out, c(1, order(as.numeric(gsub("\D+", "", names(out)[-1])))+1))
out
# id x.1 y.1 x.2 y.2 x.3 y.3
#1: 1 0 0 1 1 2 2
#2: 2 0 0 1 1 2 2
我想使用 reshape2 将 table 转换为宽格式。我希望在 vars 上对列进行排序,如下所示:
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
这样投射:
# 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
x 后跟 y,对于每个样本。
现在我正在使用 dcast 并获得以下输出:
dcast(as.data.table(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
但我希望它是x.1, y.1, x.2, y.2
等等
我可以通过重塑(原始)来做到这一点,但是我的数据花费的时间太长了(超过 50 万行,每个 table 需要 15 分钟以上,加上 20+GB 的内存)
reshape(data, idvar = id, timevar = "rater", direction = "wide")
谢谢!
一个选项是提取列名的数字部分,order
out <- dcast(as.data.table(data), id~rater, value.var=c("x", "y"), sep=".")
setcolorder(out, c(1, order(as.numeric(gsub("\D+", "", names(out)[-1])))+1))
out
# id x.1 y.1 x.2 y.2 x.3 y.3
#1: 1 0 0 1 1 2 2
#2: 2 0 0 1 1 2 2