1

How to set levels in specific order? The desired order of levels are - "CA", "IN", "FL" "NY"

library(dplyr)

tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
  mutate(states_fct = factor(states))
SiH
  • 1,378
  • 4
  • 18

3 Answers3

2

Use the levels = argument.

tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
  mutate(states_fct = factor(states, levels = c("CA", "IN", "FL", "NY"))
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
2

You can use ordered to express that you want an ordered factor:

states = ordered(c("FL", "NY", "CA", "IN"), levels = c("CA", "IN", "FL", "NY"))
str(states)
Bernhard
  • 4,272
  • 1
  • 13
  • 23
1

We could use fct_relevel from forcats package:

library(dplyr)
library(forcats)
tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
    mutate(states_fct = factor(states)) %>% 
    mutate(states_fct = fct_relevel(states_fct, c("CA", "IN", "FL", "NY")))

levels(tbl$states_fct)

Output:

  states states_fct
  <chr>  <fct>     
1 FL     FL        
2 NY     NY        
3 CA     CA        
4 IN     IN        

> levels(tbl$states_fct)
[1] "CA" "IN" "FL" "NY"
TarJae
  • 72,363
  • 6
  • 19
  • 66