Home > Software engineering >  Rearange columns by name patterns (Suffix) in R
Rearange columns by name patterns (Suffix) in R

Time:01-03

I have a dataframe of the following form:

df <- data.frame(colA_February = sample(1:10, 4),
                 colB_February = sample(1:10, 4),
                 colA_September = sample(1:10, 4),
                 colB_September = sample(1:10, 4))

> df
  colA_February colB_February colA_September colB_September
1             3            10              6              8
2             5             9              2              4
3            10             5              1              9
4             9             7              8             10

I would like to reorder the columns, such that after each 'February' column, the corresponding 'September' column follows. The final data frame should look like this:

  colA_February colA_September colB_February colB_September
1             7              6             6              3
2             9              8             4              1
3             2              1             7             10
4            10             10             5              7

I know I could order the columns manually but I want to have a flexible solution. Thanks in advance!

CodePudding user response:

We could use select in combination with order:

library(dplyr)
df %>% 
  select(order(colnames(.)))

 colA_February colA_September colB_February colB_September
1            10              3             7              6
2             2              4             3              8
3             8              1             9              3
4             9              8             6              4

CodePudding user response:

We may use month.name to match and order the suffix

library(dplyr)
df %>%
   dplyr::select(order(trimws(names(.), whitespace = "_.*")), 
    order(match(trimws(names(.), whitespace = ".*_"), month.name)))

-output

   colA_February colA_September colB_February colB_September
1             5              2            10              4
2             2              3             9              9
3             6              6             5              1
4            10              4             1              3
  • Related