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

Sort dataframe by custom order

I have a dataframe that contains a rating column.

I would like to sort using a custom order, e.g.
AAA, AA, A, BBB, BB, B

However, default R sorting (using dplyr::arrange) results in
A AA AAA B BB BBB

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

data.frame(Rating=c('AAA','AA','A','B','BB','BBB'),
           Value1=c(1,2,3,4,5,6),
           Value2=c(2,3,4,5,3,2)) %>% 
           arrange(Rating)

I found many links referring to same problem but they are not related to dataframe eg
customize the sort function in R

How can I sort my data using a custom order?

>Solution :

If you know the complete list of possible ratings, the easiest way is to make it a factor with the values in order, e.g.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
data.frame(Rating=factor(c('A', 'AA','AAA','B','BB','BBB'),
                         levels=c('AAA','AA','A','BBB','BB','B')),
       Value1=c(1,2,3,4,5,6),
       Value2=c(2,3,4,5,3,2)) %>% 
       arrange(Rating)
#>   Rating Value1 Value2
#> 1    AAA      3      4
#> 2     AA      2      3
#> 3      A      1      2
#> 4    BBB      6      2
#> 5     BB      5      3
#> 6      B      4      5

Created on 2022-01-20 by the reprex package (v2.0.1)

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