将数据帧中的列重新排列为指定的顺序 [英] Reorder a column in a dataframe to a specified order

查看:99
本文介绍了将数据帧中的列重新排列为指定的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据帧,每行都有一个值,每行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中指定的顺序排序,而不是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆