Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort columns of a dataframe by column name

Tags:

sorting

r

dataset

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 

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

like image 380
John Clark Avatar asked Sep 07 '11 13:09

John Clark


People also ask

How do I sort columns in a data frame?

Sorting the Columns of Your DataFrame You can also use the column labels of your DataFrame to sort row values. Using . sort_index() with the optional parameter axis set to 1 will sort the DataFrame by the column labels. The sorting algorithm is applied to the axis labels instead of to the actual data.

How do I sort column names?

Select a cell in the column you want to sort. On the Data tab, in the Sort & Filter group, click Sort. In the Sort dialog box, under Column, in the Sort by or Then by box, select the column that you want to sort by a custom list. Under Order, select Custom List.


1 Answers

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.

like image 65
James Avatar answered Sep 18 '22 05:09

James