我有一个数据帧,其中每行都有一个值,每个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的索引列按order指定的顺序排序,而不是DF的索引列按1,2,3,4,5,6,7,8,9,10排序。
如有任何建议,我们将不胜感激!
发布于 2015-02-11 14:40:35
您只需将index转换为ord,并将级别设置为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)发布于 2015-02-11 15:00:36
以下是我的建议:
#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)发布于 2015-02-11 14:56:58
在不更改原始数据的情况下,您可以在sort=FALSE中使用merge
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 etchttps://stackoverflow.com/questions/28447991
复制相似问题