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.
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))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With