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
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)