将数据帧中的列重新排列为指定的顺序 [英] Reorder a column in a dataframe to a specified order
问题描述
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中指定的顺序排序,而不是DF的索引列被排序为1,2,3,4,5,6,7, 8,9,10。
任何建议将不胜感激!
p>您可以简单地将 index
转换为 ord
中的级别,然后将数据排序为
DF $ index< - factor(DF $ index,levels = ord)
DF [order(DF $索引),]
如果您不想改变原始数据 em>您可以简单地创建一个单独的索引,如
indx< - factor(DF $ ind ex,levels = ord)
DF [order(indx),]
通过 setorder
从 data.table
包
$中的引用订购您的数据集b $ b
library(data.table)
setorder(setDT(DF)[,index:= factor(index,levels = ord)],index)
I have a data frame, where every row has a value, and every block of 100 rows has an index (between 1 and 10). I would like to sort the index blocks in a particular order, but am unsure how to do that:
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)
So basically, I would like the index column of DF to be ordered in blocks of the order specified in ord, instead of the index column of DF being ordered as 1,2,3,4,5,6,7,8,9,10.
Any advice would be appreciated!
You could simply convert index
to factor and set the levels as in ord
order and then sort the data as in
DF$index <- factor(DF$index, levels = ord)
DF[order(DF$index), ]
If you don't want to "alter your original data" you could simply create a separate index as in
indx <- factor(DF$index, levels = ord)
DF[order(indx), ]
Additional otion is to order your data set by reference using setorder
from the data.table
package
library(data.table)
setorder(setDT(DF)[, index := factor(index, levels = ord)], index)
这篇关于将数据帧中的列重新排列为指定的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!