8.9 Change the order of values within a factor - fct_relevel()

The default order for levels with factor() is alphabetical. We often want to reorder the levels in a factor when plotting, or when performing a regression analysis and we want to specify the reference level.

The order can be checked using levels().

# dss - disease specific survival
meldata$status_dss %>% levels()
## [1] "Died melanoma" "Alive"

The reason “Alive” is second, rather than alphabetical, is it was recoded from “2” and that order was retained. If, however, we want to make comparisons relative to “Alive”, we need to move it to the front by using fct_relevel().

meldata <- meldata %>% 
  mutate(status_dss = status_dss %>%
           fct_relevel("Alive")
         )

Any number of factor levels can be specified in fct_relevel().