将数据框中的列按指定顺序重新排列

3

我有一个数据框,其中每行都有一个值,每100行为一块,并且每个块都有一个索引(介于1和10之间)。我想按特定顺序对索引块进行排序,但不确定如何做到这一点:

N=1000
value = runif(N, min=0, max=100)
index = rep(1:10, each=100)
DF=data.frame(value,index)
ord = c(1,4,6,3,7,9,8,2,5,10)

基本上,我希望DF的索引列按照ord指定的顺序分块排序,而不是按照1,2,3,4,5,6,7,8,9,10的顺序排列。如果您有任何建议,请告诉我!

1
在编写数据时,尽量限制只使用所需的数据。以2个为一组的20个案例与以100个为一组的1000个案例同样有效。 - thelatemail
3个回答

4
你可以将index转换为因子,并按照ord的顺序设置级别,然后像下面这样对数据进行排序。
DF$index <- factor(DF$index, levels = ord)
DF[order(DF$index), ]

如果您不想“更改原始数据”,您可以像以下这样简单地创建一个单独的索引:

indx <- factor(DF$index, levels = ord) 
DF[order(indx), ]

另一种选择是使用 data.table 包中的 setorder ,按照参考文献对数据集进行排序。

library(data.table)
setorder(setDT(DF)[, index := factor(index, levels = ord)], index)

1
我也会这样做。 - akrun

2

这是我的提案:

#Genreate the data    
N<-1000
value <- runif(N, min=0, max=100)
index <- rep(1:10, each=100)
DF<-data.frame(value,index)
ord <- c(1,4,6,3,7,9,8,2,5,10)

#Create a list with the data sorted by the provided order
newDF<-apply(matrix(ord,,ncol=1),1,function(x) DF[DF[,2]==x,])

#Unlist the list into a dataframe
do.call(rbind.data.frame,newDF)

1
不改变原始数据,您可以使用mergesort=FALSE:
merge(data.frame(index=ord), DF, by="index", sort=FALSE)

#   ord    value
#1    1 37.29915
#2    1 30.09436
#3    4 18.05961
#4    4 46.73024
#5    6 93.15545
#6    6 69.33484
#7    3 70.92353
#8    3 81.63010
#9    7 22.23649
#10   7 32.36390
# etc etc

不修改您的原始数据”是指我的答案吗?你知道我可以直接这样做 indx <- factor(DF$index, levels = ord) ; DF[order(indx), ],对吧 :)?不过确实是个好解决方案。 - David Arenburg
@DavidArenburg - 这只是玩笑话,没有任何不敬意 :-P - thelatemail

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接