简体   繁体   中英

Set a level of a factor to be the last

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?

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 (eg, last = 2 would move the second level to the last).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM