如何按频率对因子值列重新排序 - 按升序排列?
虽然forcats包提供了一种基于其频率(fct_infreq())重新排序因子的明确方法,但它在降低频率顺序时这样做.我需要因子频率/计数的相反顺序.
例如
library(forcats)
set.seed(555)
df <- data.frame(x=factor(sample(as.character(1:10), 100, replace=TRUE)))
table(df$x)
1 10 2 3 4 5 6 7 8 9
9 10 12 14 10 10 5 12 8 10
levels(fct_infreq(df$x))
[1] "3" "2" "7" "10" "4" "5" "9" "1" "8" "6"
Run Code Online (Sandbox Code Playgroud)
是否有一种简单的方法来翻转排序,以便最不频繁的因素("6")是第一个,最频繁的("3")是最后的?
这可以通过使用fct_rev简单地完成,如下所示:
levels(fct_rev(fct_infreq(df$x)))
[1] "6" "8" "1" "9" "5" "4" "10" "7" "2" "3"
Run Code Online (Sandbox Code Playgroud)