rdataframe

Ordering table by a specific repeated sequence of values


I have a data frame:

df <- data.frame(col1 = c(1,1,1,1,2,2,2,2,3,3,3,3),
                 col2 = rep(c("A", "B", "C", "D"), 3))


   col1 col2
1     1    A
2     1    B
3     1    C
4     1    D
5     2    A
6     2    B
7     2    C
8     2    D
9     3    A
10    3    B
11    3    C
12    3    D

I want to reorder the data frame such that the repeated sequence in col2 follows the next pattern: A, C, B, D. The desire table is:

df_result <- data.frame(col1 = c(1,1,1,1,2,2,2,2,3,3,3,3),
                        col2 = rep(c("A", "C", "B", "D"), 3))

   col1 col2
1     1    A
2     1    C
3     1    B
4     1    D
5     2    A
6     2    C
7     2    B
8     2    D
9     3    A
10    3    C
11    3    B
12    3    D


Solution

  • A simple way is to convert col2 to a factor and reorder the levels in the way you want.

    library(dplyr)
    
    mutate(df, col2=factor(col2, levels=c("A","C","B","D"))) |>
      arrange(col1, col2)
    
       col1 col2
    1     1    A
    2     1    C
    3     1    B
    4     1    D
    5     2    A
    6     2    C
    7     2    B
    8     2    D
    9     3    A
    10    3    C
    11    3    B
    12    3    D