假设我的数据框中有一个如下所示的变量:
x <- rep(seq(10, 50, by = 10), each = 20) %>% factor() %>% forcats::fct_shuffle()
现在,我想按升序重新排列级别。从理论上讲,我可以再次使用factor
并手动定义级别:
factor(x, levels = c(10, 20, 30, 40, 50))
但从长远来看,它似乎是枯草酮,而且含量可能更高。那么如何按升序对关卡进行重新排序?
答案 0 :(得分:2)
也许:
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()