Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Natural sorting to sort columns of a dataframe by column name

I would like to arrange the columns of a dataframe by the column names. Is it possible to do this using natural sorting?

My columns are currently arranged numerically across the data from:

Blockquote

#   A1 A10 A11 A12 A2 A3 A4 ...
# 1 
# 2 
# .
# .
# .

I would like to rearrange the columns so that they are arranged by natural sorting as below:

#   A1 A2 A3 A4 A10 A11 A12 ...
# 1 
# 2 
# .
# .
# .

Please note that my datasets are huge with hundreds of columns so the process needs to be automated.

like image 805
David M Avatar asked Nov 15 '25 23:11

David M


1 Answers

mixedsort in the gtools package does exactly this.

library(gtools)
CNames = c("A1", "A10", "A11", "A12", "A2", "A3", "A4")
mixedsort(CNames)
[1] "A1"  "A2"  "A3"  "A4"  "A10" "A11" "A12"

Of course, to rearrange your data.frame, you want something like

df = df[,mixedsort(colnames(df))]
like image 190
G5W Avatar answered Nov 18 '25 14:11

G5W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!