通过增加频率重新排序因子

Reorder factors by increasing frequency

如何按频率对因子值列重新排序 - 按升序排列?

虽然 forcats 包提供了一种根据频率 (fct_infreq()) 对因子重新排序的显式方法,但它是以降序排列的。我需要因子 frequency/counts.

的倒序

例如

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" 

是否有一种简单的方法来翻转顺序,使出现频率最低的因素(“6”)排在第一位,出现频率最高的因素(“3”)排在最后?

只需使用 fct_rev 即可完成,如下所示:

levels(fct_rev(fct_infreq(df$x)))

[1] "6"  "8"  "1"  "9"  "5"  "4"  "10" "7"  "2"  "3" 

或者,您可以在 base R 中通过排序和重置级别来完成。

xLev = names(table(df$x))[order(table(df$x))]
df$x = factor(df$x, levels=xLev)
table(df$x)
 6  8  1 10  4  5  9  2  7  3 
 5  8  9 10 10 10 10 12 12 14 
with(data.frame(table(df$x)), setNames(sort(Freq), Var1[order(Freq)]))
# 6  8  1 10  4  5  9  2  7  3 
# 5  8  9 10 10 10 10 12 12 14