簡體   English   中英

將因子水平設置為最后一個

[英]Set a level of a factor to be the last

我知道該功能重新設置將指定的級別設置為第一個。 我想知道是否有將指定級別設置為最后一個的內置函數。 如果沒有,編寫這種功能的有效方法是什么?

沒有內置功能。 您可以這樣做:

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

我有點傻,因為當我可以對stats:::relevel.factor進行微小修改時,我只是寫了出來。 經過relevel的解決方案如下所示:

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])])
}

它檢查更多的輸入,並接受一個數字(例如, last = 2會將第二級移到最后)。

forcats軟件包具有一個功能可以forcats地完成此任務。

f <- gl(2, 1, labels = c("b", "a"))

forcats::fct_relevel(f, "b", after = Inf)

#> [1] b a
#> Levels: a b

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM