本文介绍了R:从宽到长整形,无法正确订购的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将数据从宽到长整形,但顺序不正确:
I reshaped my data from wide to long, but I can't get the order right:
data <- as.data.frame(matrix(c(rep(1:5),0,0,0,5,1,0,0,0,5,0),5,3))
colnames(data) <- c("id", "x1.a", "x3.a")
print(data)
# id x1.a x3.a
# 1 1 0 0
# 2 2 0 0
# 3 3 0 0
# 4 4 5 5
# 5 5 1 0
reshaped <- reshape(data,
varying = 2:3,
v.names = "x.a",
times = c(1,3),
timevar = "time",
idvar = "id",
direction = "long")
print(reshaped)
# id time x.a
# 1.1 1 1 0
# 2.1 2 1 0
# 3.1 3 1 0
# 4.1 4 1 5
# 5.1 5 1 1
# 1.3 1 3 0
# 2.3 2 3 0
# 3.3 3 3 0
# 4.3 4 3 5
# 5.3 5 3 0
我要输入 x1.a
和 x3.a
将按 id
,例如:
I want the values in x1.a
and x3.a
to be grouped by id
, like so:
# id time x.a
# 1.1 1 1 0
# 1.3 1 3 0
# 2.1 2 1 0
# 2.3 2 3 0
# 3.1 3 1 0
# 3.3 3 3 0
# 4.1 4 1 5
# 4.3 4 3 5
# 5.1 5 1 1
# 5.3 5 3 0
有人可以帮忙吗?谢谢。
Can anyone help? Thanks.
推荐答案
您的意思是只想对数据框进行排序?原因很简单:
You mean you just want to sort the data frame? Cause that's pretty easy:
> reshaped[with(reshaped,order(id,time)),]
id time x.a
1.1 1 1 0
1.3 1 3 0
2.1 2 1 0
2.3 2 3 0
3.1 3 1 0
3.3 3 3 0
4.1 4 1 5
4.3 4 3 5
5.1 5 1 1
5.3 5 3 0
这篇关于R:从宽到长整形,无法正确订购的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!