amisos55
amisos55

Reputation: 1979

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!

Upvotes: 2

Views: 978

Answers (1)

lovalery
lovalery

Reputation: 4652

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

Reprex

  • Code
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))
  • Output
#> [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)

Upvotes: 1

Related Questions