基于字符向量对数据帧进行重新排序 [英] Reorder Dataframe based on Character Vector

查看:46
本文介绍了基于字符向量对数据帧进行重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这应该非常简单,但是我找不到解决方法。

I think this should be really simple, but I cannot find a way to do this.

我想根据一个因素对数据框进行重新排序。到目前为止,我能找到的所有答案都提供了逻辑排序,但这是任意的,并且由数字和字母组成。也许是一个问题,因为它是一个因素而不是向量

I want to reorder a dataframe based on a factor. All the answers I can find so far provide logical sorting, but this is arbitrary, and a mixture of numbers and letters. Maybe it's a problem because it is a factor not a vector? But none of the answers for vectors seem to work either.

任何建议将不胜感激!

示例数据
(注意;该数据仅用于此问题,在我的真实代码中,数据帧是其他一些计算的输出,因此我不能只是在开始时就将名称更改为明智的名称)

Example data (note; this data is just for this question, in my real code the dataframe is the output of some other calculations and so I can't just alter the names to something sensible right at the start)

DATA<- data.frame(This=c("120", "60", "90", "OG"), That=c(453, 679,12,252))

DATA

  This That
1  120  453
2   60  679
3   90   12
4   OG  252

我要按60-90-120- OG,即

I want to sort it in the order 60 - 90 - 120 - OG, i.e.

  This That
1  60   679
2  90   12
3  120  453
4  OG   252

编辑:这不是重复项题。如上所述,在下面的注释中,排序是任意的。字典排序假设行名称是相互关联的,在此情况并非如此。我可以将行标记为( unicorn, 18.1, TREES, 234234235)并按( 234234235,独角兽,树, 18.1)

This is not a duplicate question. As explained above, and in the comment below, the sorting is arbitrary. Lexicographical sorting assumes the row names are inter-related, that isn't the case here. I could have labelled the rows ("unicorn", "18.1", "TREES", "234234235") and wanted them in the order ("234234235", "unicorn", "TREES", "18.1")

推荐答案

您可以调整带有 factor 变量的顺序如下:

You can adjust the order with the factor variable as follows:

DATA$This <- factor(DATA$This, levels=c("60", "90", "120", "OG"))

请注意,这不会更改标签值:

Note that this doesn't change the label values:

DATA
  This That
1  120  453
2   60  679
3   90   12
4   OG  252

但是它会更改映射到这些标签的基础整数,以便您可以根据需要对数据进行排序:

But it changes the underlying integers that are mapped to those labels, so that you can order the data as you wanted:

DATA[order(DATA$This),]
  This That
2   60  679
3   90   12
1  120  453
4   OG  252

这篇关于基于字符向量对数据帧进行重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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