Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading