0

My data has more than 10 columns, an example would be the following;

I have a data frame like this

> set.seed(1)
> data.frame(`1`=rnorm(3), `2`=rnorm(3), `4`=rnorm(3), `3`=rnorm(3), check.names=FALSE)
           1          2         4          3
1 -0.6264538  1.5952808 0.4874291 -0.3053884
2  0.1836433  0.3295078 0.7383247  1.5117812
3 -0.8356286 -0.8204684 0.5757814  0.3898432

And I'd like to reorder the column names in numerical order to produce this

           1          2         3          4
1 -0.6264538  1.5952808 -0.3053884  0.4874291
2  0.1836433  0.3295078  1.5117812  0.7383247
3 -0.8356286 -0.8204684  0.3898432  0.5757814
MB232
  • 33
  • 7
  • Does this answer your question? [Sort columns of a dataframe by column name](https://stackoverflow.com/questions/7334644/sort-columns-of-a-dataframe-by-column-name) – harre Jun 16 '22 at 13:31
  • Yes it isn't ideal, but a little bit unavoidable in this case because of the data I'm working on. Are there any solutions that can work for 10 or more columns? – MB232 Jun 16 '22 at 13:31
  • You could probably use leading zeros. – harre Jun 16 '22 at 13:33

5 Answers5

1

In base R

df[, order(names(df))]

           1           2           3         4
1 -0.6212406 -0.04493361  0.78213630 0.8212212
2 -2.2146999 -0.01619026  0.07456498 0.5939013
3  1.1249309  0.94383621 -1.98935170 0.9189774
Chamkrai
  • 5,912
  • 1
  • 4
  • 14
1

One option is to use dplyr

library(dplyr)
df %>% select(sort(colnames(.)))
         1          2           3          4
1 0.3611660 -2.9488152 -0.02784209 -0.2030595
2 0.0718857  0.1729129  1.87656950  0.5255996
3 0.5270741 -0.8096340 -0.22971223  0.8571217
user438383
  • 5,716
  • 8
  • 28
  • 43
1

Another possible solution, based on dplyr:

library(dplyr)

df %>% 
  relocate(order(names(.)))

#>            1          2          3         4
#> 1 -0.6264538  1.5952808 -0.3053884 0.4874291
#> 2  0.1836433  0.3295078  1.5117812 0.7383247
#> 3 -0.8356286 -0.8204684  0.3898432 0.5757814
PaulS
  • 21,159
  • 2
  • 9
  • 26
1

Credit to @RitchieSacramento for this working answer.

The following works;

df[, order(as.numeric(names(df)))]
MB232
  • 33
  • 7
0

data.table option using setcolorder:

library(data.table)
setDT(df)
setcolorder(df, order(colnames(df)))
df

Output:

           1          2          3         4
1 -0.6264538  1.5952808 -0.3053884 0.4874291
2  0.1836433  0.3295078  1.5117812 0.7383247
3 -0.8356286 -0.8204684  0.3898432 0.5757814
Quinten
  • 35,235
  • 5
  • 20
  • 53