5.2 Sorting

5.2.1 Sorting by frequency, appearance, or numeric order

fct_infreq() reorder factor levels by frequency of each level, NA levels come last regardless of frequency.

fct_inorder(): sort a factor by the order in which they first appear. This can be useful when dealing with time series data.

fct_inseq(): sort a factor by numeric value of a level. This is only applicable when at least one existing level can be coercible to numeric

5.2.2 Sorting by another variable

fct_reorder() 其实就是 base::reorder()forcats 中的实现,它根据因子在其他变量上的统计量(中位数、平均数、···)的值对各个水平排序,当绘制非频次条形图时很有用。

Use .fun to set a summarizing function (defaults to median()), .desc = TRUE to sort the factor in descending order, NA levels always come the last regardless of the corresponding variable, fct_explicit_na() in Section 5.3.4 fix this.

Sometimes a factor is mapped to a non-position aesthetic, fct_reorder2(.f, .x, .y, .fun = last2) is designed for this kind of 2d displays of a factor. last2() and first2() are helpers for fct_reorder2(); last2() finds the last value of .y when sorted by .x; first2() finds the first value.

5.2.3 Sorting manually

fct_infreq()fct_reorder() 排序的依据是明确的,但我们有时也需要人工指定、修改排序结果。fct_relevel()接受一个向量调整因子水平的排序。

这个例子中使用forcats::gss_cat,该数据集是综合社会调查(General Social Survey)的一份抽样。综合社会调查是美国芝加哥大学的独立研究组织 NORC 进行的一项长期美国社会调查

在这个数据集中,因子 rincome 个水平的顺序排列是正确的。为了演示fct_relevel()的用法,先用 fct_shuffle() 打乱该因子的水平顺序:

fct_relevel() 中,通过一个包含水平名称的向量调整排序。默认情况下,向量中的第一个水平被调整到第一个位置上,第二个水平被调整到第二个位置上,以此类推,你只需要指定那些需要调整的水平。可以通过 after 指定向量中各水平被调整到什么地方, after = -Inf 时第一个水平将被调整到排序的最后一位: