按照频率递增重新排序因子。

5

如何按出现频率重新排序因子值列-按递增顺序?

尽管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" 

有没有一种简单的方法可以翻转顺序,使得出现次数最少的因子(“6”)排在前面,最常见的因子(“3”)排在最后?
3个回答

9

您可以通过以下方式简单地使用fct_rev来实现:

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

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

3
或者,您可以通过排序和重置级别来使用基本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 

0
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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接