Reorder the levels of a factor into any order you specify.
Usage
permuteLevels(x, perm, ordered = is.ordered(x), invert = FALSE)Arguments
- x
A factor.
- perm
An integer vector of the same length as
nlevels(x). Wheninvert = FALSE(the default),perm[k]gives the index of the old level that should appear in positionkof the new ordering. Wheninvert = TRUE,perm[k]gives the new position to assign to thek-th old level.- ordered
Set to
TRUEto return an ordered factor. Defaults tois.ordered(x), preserving the ordered status of the input.- invert
Set to
TRUEto apply the inverse ofperm. See thepermdescription above and the examples below.
Details
Similar to relevel, but more general:
relevel can only move one level to the front, whereas
permuteLevels can place the levels in any order. This is useful
when you want to control the order in which levels appear on a plot axis
or in a table.
Examples
# factor with levels a, b, c, d, e, f (in that order)
x <- factor(c(1, 4, 2, 2, 3, 3, 5, 5, 6, 6), labels = letters[1:6])
levels(x)
#> [1] "a" "b" "c" "d" "e" "f"
# move level e to position 1, c to position 2, b to 3, a to 4, d to 5, f to 6
permuteLevels(x, perm = c(5, 3, 2, 1, 4, 6))
#> [1] a d b b c c e e f f
#> Levels: e c b a d f
# using invert = TRUE: move level a to position 5, b to 3, c to 2, etc.
permuteLevels(x, perm = c(5, 3, 2, 1, 4, 6), invert = TRUE)
#> [1] a d b b c c e e f f
#> Levels: d c b e a f