假设我的数据框中有一个变量,如下所示:
x <- rep(seq(10, 50, by = 10), each = 20) %>% factor() %>% forcats::fct_shuffle()
现在,我想按升序重新排列级别。从理论上讲,我可以factor
再次使用并手动定义级别:
factor(x, levels = c(10, 20, 30, 40, 50))
但从长远来看,它似乎很麻烦,可能有更多的关卡。那么如何按升序重新排序级别?
也许:
factor(x, levels = sort(levels(x)))
# [1] 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
# [41] 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40
# [81] 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50
# Levels: 10 20 30 40 50
与forcats
:
forcats::fct_inorder(x)
数据:
x <- rep(seq(10, 50, by = 10), each = 20) %>% factor() %>% forcats::fct_shuffle()