combine fct_relevel with fct_expand to create a factor order with empty factor levels

52 Views Asked by At

I have a dataset that does not contain now but later a defined order.

For instance

library(tidyverse)

x <- c("a")

fct_relevel("d", c("a", "b", "c", "d"))
[1] d
Levels: d
Warning message:
3 unknown levels in `f`: a, b, and c

fct_expand("d", c("a", "b", "c", "d"))
[1] d
Levels: d a b c

How can I use fct_relevel() together with fct_expand() to pre-define the order in the order of the levels "a b c d" even if the levels are unknown at the current time? (Another dplyr solution would also be fine)

Thank you very much!

1

There are 1 best solutions below

1
Adriano Mello On

If you're working with tibbles, you can use fct_expand and complete:

library(forcats)

# Create am ordered factor-column
aux <- tibble(x = fct("a", c("a", "b", "c", "e")))

# Add a new level indicating where it should be
new_aux <- mutate(aux, x = fct_expand(x, "d", after = 3))

# Complete all factor cases
new_aux <- complete(new_aux, x = levels(x))

> new_aux
# A tibble: 5 × 1
  x    
  <chr>
1 a    
2 b    
3 c    
4 d    
5 e