dply: order columns alphabetically in R

Solution 1:

Try this

df %>% select(noquote(order(colnames(df))))

or just

df[,order(colnames(df))]

Solution 2:

An alternative way to do this in dplyr is:

iris %>% 
  select(sort(current_vars()))

current_vars() returns column names such that they're sortable, and select() will take the vector of column names.

Solution 3:

If a specific column (or columns) has to be the first one (or last), but the rest is ordered, you can:

mtcars %>% tibble %>% 
  select("hp", sort(colnames(.)))