I know that the function relevel sets an specified level to be the first. I would like to know if there is a built-in function that sets an specified level to be the last. If not, what is an efficient way to write such a function?
2 Answers
The package forcats
has a function that does this neatly.
f <- gl(2, 1, labels = c("b", "a"))
forcats::fct_relevel(f, "b", after = Inf)
#> [1] b a
#> Levels: a b
There is not a built-in function. You could do it like this:
lastlevel = function(f, last) {
if (!is.factor(f)) stop("f must be a factor")
orig_levels = levels(f)
if (! last %in% orig_levels) stop("last must be a level of f")
new_levels = c(setdiff(orig_levels, last), last)
factor(f, levels = new_levels)
}
x = factor(c("a", "b", "c"))
> lastlevel(x, "a")
[1] a b c
Levels: b c a
> lastlevel(x, "b")
[1] a b c
Levels: a c b
> lastlevel(x, "c")
[1] a b c
Levels: a b c
> lastlevel(x, "d")
Error in lastlevel(x, "d") : last must be a level of f
I feel a little silly because I just wrote that out, when I could have made a tiny modification to stats:::relevel.factor
. A solution adapted from relevel
would look like this:
lastlevel = function (f, last, ...) {
if (!is.factor(f)) stop("f must be a factor")
lev <- levels(f)
if (length(last) != 1L)
stop("'last' must be of length one")
if (is.character(last))
last <- match(last, lev)
if (is.na(last))
stop("'last' must be an existing level")
nlev <- length(lev)
if (last < 1 || last > nlev)
stop(gettextf("last = %d must be in 1L:%d", last, nlev),
domain = NA)
factor(f, levels = lev[c(last, seq_along(lev)[-last])])
}
It checks a few more inputs and also accepts a numeric (e.g., last = 2
would move the second level to the last).
-
1
-
It's not letting me post an edit because the change is too small but the second code block doesn't actually work unless
x
is defined globally, which seems like a mistake. I think the fix is to replacex
withf
, the parameter value for the factor. Nov 13, 2018 at 19:46