本文介绍了R:从长到宽重塑,重塑柱的顺序与原始柱顺序相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的数据摘录:

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

我从长到宽重塑了它:

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

但不是默认顺序(由 timevar 排序,即 x.1 y.1 x.2 y.2 x.3 y.3 ),我要顺序与重塑前列显示的原始顺序相同(即所有 x 全部 y x.1 x.2 x.3 y.1 y.2 y.3 )。

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).

我可以手动完成此操作,但是我需要重整100多个列。我试过?reshape 但找不到任何东西。

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

谢谢!

推荐答案

这可以通过使用 data.table dcast 来实现。 $ c>可以使用多个 value.var

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

这篇关于R:从长到宽重塑,重塑柱的顺序与原始柱顺序相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 02:48