[英]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.