Search code examples
rdataframedplyrtidyverse

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?


Solution

  • Use mixedsort instead of mixedorder

    library(gtools)
    library(dplyr)
    df %>%
        select(mixedsort(names(.)))
       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
    
    

    The issue with mixedorder by removing the first column is that it returns an index starting from 1, which needs to start from 2 i.e. add 1

    df %>%
       select(1, mixedorder(names(.)[-1])+1)
      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