runordered

change the order of a factor character vector


I have a character factor-leveled vector.

cat <- as.factor(c("AS-GEN-SUM-10-Fall", "AS-GEN-SUM-3-Fall","AS-GEN-SUM-4-Fall","AS-GEN-SUM-5-Fall"))

cat
[1] AS-GEN-SUM-10-Fall AS-GEN-SUM-3-Fall  AS-GEN-SUM-4-Fall  AS-GEN-SUM-5-Fall 
Levels: AS-GEN-SUM-10-Fall AS-GEN-SUM-3-Fall AS-GEN-SUM-4-Fall AS-GEN-SUM-5-Fall

As seen, the order starts with the number -10- instead of -3-. R naturally order them by the first number even though 10 is larger than 3.

Is there a way to change the order without specifying each name? Any ideas?

Thanks!


Solution

  • Please, find below one possible solution using the mixedsort() function from the gtools library.

    Reprex

    library(gtools)
    
    factor(mixedsort(c("AS-GEN-SUM-10-Fall", "AS-GEN-SUM-3-Fall","AS-GEN-SUM-4-Fall","AS-GEN-SUM-5-Fall"), decreasing = TRUE))
    
    #> [1] AS-GEN-SUM-3-Fall  AS-GEN-SUM-4-Fall  AS-GEN-SUM-5-Fall  AS-GEN-SUM-10-Fall
    #> 4 Levels: AS-GEN-SUM-10-Fall AS-GEN-SUM-3-Fall ... AS-GEN-SUM-5-Fall
    

    Created on 2022-02-11 by the reprex package (v2.0.1)