Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to order columns by names containing special symbols R

I have dataframe below:

df <- data.frame(aa = rep(1,4),
                ae = rep(2,4),
                dd = rep(3,4),
                `aa%` = rep(11,4),
                `ae%` = rep(22,4),
                `dd%` = rep(33,4))

  aa ae dd aa. ae. dd.
1  1  2  3  11  22  33
2  1  2  3  11  22  33
3  1  2  3  11  22  33
4  1  2  3  11  22  33

I want to order the columns to become like

  aa aa. ae ae. dd dd.
1  1  11  2  22  3  33
2  1  11  2  22  3  33
3  1  11  2  22  3  33
4  1  11  2  22  3  33

so I did

library(dplyr)
library(gtools)
df %>%
  select(1, mixedorder(names(.)[-1]))

but this gives

  aa dd aa. ae ae.
1  1  3  11  2  22
2  1  3  11  2  22
3  1  3  11  2  22
4  1  3  11  2  22

How can I get the output with desired order of columns?

like image 628
Mathica Avatar asked Dec 29 '25 16:12

Mathica


1 Answers

With dplyr we could:

library(dplyr)

df %>% select(order(colnames(df)))
  aa aa. ae ae. dd dd.
1  1  11  2  22  3  33
2  1  11  2  22  3  33
3  1  11  2  22  3  33
4  1  11  2  22  3  33
like image 182
TarJae Avatar answered Jan 01 '26 04:01

TarJae



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!