本文介绍了通过增加频率重新排序因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何按频率对因子值列重新排序 - 按升序排列?
How do I reorder factor-valued columns by frequency - in increasing order?
虽然 forcats 包提供了一种基于频率重新排序因子的明确方法(fct_infreq()),它以降频顺序进行.我需要因子频率/计数的相反顺序.
While the forcats package provides an explicit way to reorder a factor based on its frequency (fct_infreq()), it does so in decreasing frequency order. I need the reverse order of the factor 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")在后?
Is there a simple way to flip the ordering so that the least frequent factor ("6") is first and the most frequent ("3") last?
推荐答案
这可以通过使用 fct_rev 如下:
This can be done simply by using fct_rev as follows:
levels(fct_rev(fct_infreq(df$x)))
[1] "6" "8" "1" "9" "5" "4" "10" "7" "2" "3"
这篇关于通过增加频率重新排序因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!