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
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
Credit to @RitchieSacramento for this working answer.
The following works;
df[, order(as.numeric(names(df)))]
CodePudding user response:
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