按列名排序数据框的列 [英] Sort columns of a dataframe by column name

查看:131
本文介绍了按列名排序数据框的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的问题,但我不知道如何按字母顺序排列列。

This is possibly a simple question, but I do not know how to order columns alphabetically.

test = data.frame(C = c(0, 2, 4, 7, 8), A = c(4, 2, 4, 7, 8), B = c(1, 3, 8, 3, 2))

#   C A B
# 1 0 4 1
# 2 2 2 3
# 3 4 4 8
# 4 7 7 3
# 5 8 8 2

我喜欢按字母顺序排列列,以实现

I like to order the columns by column names alphabetically, to achieve

#   A B C
# 1 4 1 0
# 2 2 3 2
# 3 4 8 4
# 4 7 3 7
# 5 8 2 8

对于其他人我想要我自己定义订单:

For others I want my own defined order:

#   B A C
# 1 4 1 0
# 2 2 3 2
# 3 4 8 4
# 4 7 3 7
# 5 8 2 8



<请注意,我的数据集是巨大的,有10000个变量。所以这个过程需要更自动化。

Please note that my datasets are huge, with 10000 variables. So the process needs to be more automated.

推荐答案

您可以使用订单 名称,并使用它来排列子集时的列:

You can use order on the names, and use that to order the columns when subsetting:

test[ , order(names(test))]
  A B C
1 4 1 0
2 2 3 2
3 4 8 4
4 7 3 7
5 8 2 8

对于您自己定义的订单,您需要定义自己的将名称映射到排序。这将取决于你想如何做到这一点,但是交换任何功能将会与订单以上应该给你想要的输出。

For your own defined order, you will need to define your own mapping of the names to the ordering. This would depend on how you would like to do this, but swapping whatever function would to this with order above should give your desired output.

你可以看一下根据指定所需顺序的目标向量对数据框的行进行排序,即您可以匹配您的数据框名称针对包含所需列顺序的目标向量。

You may for example have a look at Order a data frame's rows according to a target vector that specifies the desired order, i.e. you can match your data frame names against a target vector containing the desired column order.

这篇关于按列名排序数据框的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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