HaagenDaz
HaagenDaz

Reputation: 461

how to sort data frame by column names in R?

How can I sort the below data frame df to df1?

df
a1 a4 a3 a5 a2

sorted data frame

df1
a1 a2 a3 a4 a5

Upvotes: 1

Views: 3770

Answers (3)

meriops
meriops

Reputation: 1037

Assuming there is no "hole" in the numbers suffixing the columns names, you can also use dplyr: library(dplyr) df1 <- select(df, num_range("a", 1:4))

Upvotes: 0

mtoto
mtoto

Reputation: 24198

In base R, assuming the numbers in the colnames don't go into double digits.

df
#  a1 a4 a3 a5 a2
#1  1  4  3  5  2

df[, order(names(df))]
#  a1 a2 a3 a4 a5
#1  1  2  3  4  5

Upvotes: 1

akrun
akrun

Reputation: 887851

We can use mixedorder from library(gtools)

library(gtools)
df1 <- df[mixedorder(colnames(df))]
df1
#   a1 a3 a9 a10
#1  1  3  1   2
#2  2  4  2   3
#3  3  5  3   4
#4  4  6  4   5
#5  5  7  5   6

data

df <- data.frame(a1 = 1:5, a10=2:6, a3 = 3:7, a9= 1:5)

Upvotes: 3

Related Questions