[r] 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

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

This question is related to r sorting dataset

The answer is


So to have a specific column come first, then the rest alphabetically, I'd propose this solution:

test[, c("myFirstColumn", sort(setdiff(names(test), "myFirstColumn")))]

An alternative option is to use str_sort() from library stringr, with the argument numeric = TRUE. This will correctly order column that include numbers not just alphabetically:

str_sort(c("V3", "V1", "V10"), numeric = TRUE)

# [1] V1 V3 V11


  test[,sort(names(test))]

sort on names of columns can work easily.


Here is what I found out to achieve a similar problem with my data set.

First, do what James mentioned above, i.e.

test[ , order(names(test))]

Second, use the everything() function in dplyr to move specific columns of interest (e.g., "D", "G", "K") at the beginning of the data frame, putting the alphabetically ordered columns after those ones.

select(test, D, G, K, everything())

­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­


If you only want one or more columns in the front and don't care about the order of the rest:

require(dplyr)
test %>%
  select(B, everything())

Similar to other syntax above but for learning - can you sort by column names?

sort(colnames(test[1:ncol(test)] ))

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

Using the simple following function replacement can be performed (but only if data frame does not have many columns):

test <- test[, c("A", "B", "C")]

for others:

test <- test[, c("B", "A", "C")]

Here's the obligatory dplyr answer in case somebody wants to do this with the pipe.

test %>% 
    select(sort(names(.)))

Examples related to r

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean?

Examples related to sorting

Sort Array of object by object field in Angular 6 Sorting a list with stream.sorted() in Java How to sort dates from Oldest to Newest in Excel? how to sort pandas dataframe from one column Reverse a comparator in Java 8 Find the unique values in a column and then sort them pandas groupby sort within groups pandas groupby sort descending order Efficiently sorting a numpy array in descending order? Swift: Sort array of objects alphabetically

Examples related to dataset

How to convert a Scikit-learn dataset to a Pandas dataset? Convert floats to ints in Pandas? Convert DataSet to List C#, Looping through dataset and show each record from a dataset column How to add header to a dataset in R? How I can filter a Datatable? Stored procedure return into DataSet in C# .Net Looping through a DataTable adding a datatable in a dataset How to fill Dataset with multiple tables?