Other ways of dealing with factors

  • If we want the order of the levels match the order of the first appearance in the data then use unique(), or after the fact, with fct_inorder():
f1 <- factor(x1, levels = unique(x1))
f1
## [1] Dec Apr Jan Mar
## Levels: Dec Apr Jan Mar
f2 <- x1 |> factor() |> fct_inorder()
f2
## [1] Dec Apr Jan Mar
## Levels: Dec Apr Jan Mar
levels(f2)
## [1] "Dec" "Apr" "Jan" "Mar"
  • We can also create a factor when reading your data with readr with col_factor():
csv <- "
month,value
Jan,12
Feb,56
Mar,12"
df <- read_csv(csv, col_types = cols(month = col_factor(month_levels)))

df$month
## [1] Jan Feb Mar
## Levels: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec