Let's call two levels from different factors corresponding if
they occupy the same position by order. This function takes two factors of
same length, f and f_by and returns the first one with levels reordered
such the number of positions where level of f corresponds to the level of
f_by is maximized.
Considering that as.integer() applied to a factor returns a vector of
level sequence numbers, we can say that this function maximizes the value
of sum(as.integer(f) == as.integer(f_by)). Or in case if weights are
used: sum(weights*(as.integer(f) == as.integer(f_by))).
Examples
f_by <- factor(c("b", "b", "a", "a", "a"))
f <- factor(c("blue", "blue", "red", "green", "red"))
levels(f_by)
#> [1] "a" "b"
#> [1] "a" "b"
levels(f)
#> [1] "blue" "green" "red"
#> [1] "blue" "green" "red"
# "blue" corresponds to "a" and "green" corresponds to "b"
# number if positions where levels correspond: 0/5
f_aligned <- fct_align_levels(f, f_by)
levels(f_aligned)
#> [1] "red" "blue" "green"
#> [1] "red" "blue" "green"
# same factor, only order of levels is different
# now "red" corresponds to "a" and "blue" corresponds to "b"
# number of positions where levels correspond: 4/5