2017-03-13 31 views

回答

3

沒有內置函數。你可以做這樣的:

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(x) 
    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(x, levels = lev[c(last, seq_along(lev)[-last])]) 
} 

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

+1

打我30秒! –

2

forcats有一個功能,這樣做整齊。

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

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

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