Sort columns of a dataframe by column name Sort columns of a dataframe by column name r r

Sort columns of a dataframe by column name


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

test[ , order(names(test))]  A B C1 4 1 02 2 3 23 4 8 44 7 3 75 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.


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

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


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")]