按列名对数据框的列进行排序 [英] Sort columns of a dataframe by column name
问题描述
这可能是一个简单的问题,但我不知道如何按字母顺序排列列.
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.
推荐答案
您可以在 names
上使用 order
,并在子集化时使用它对列进行排序:
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
对于您自己定义的顺序,您需要定义自己的名称到顺序的映射.这将取决于您希望如何执行此操作,但是使用上面的 order
将任何函数交换到此应该会得到您想要的输出.
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.
例如,您可以查看 根据指定所需顺序的目标向量对数据框的行进行排序,即您可以match
您的数据框names
包含所需列顺序的目标向量.
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屋!