首页 > 解决方案 > 开箱即用的功能将关卡的长尾放置在一个功能中作为“其他”?

问题描述

假设我在 dplyr 链的中间,并且想要将不太频繁级别的长尾合并到其他级别:

diamonds$clarity %>% table %>% data.frame %>% arrange(desc(Freq))
     .  Freq
1  SI1 13065
2  VS2 12258
3  SI2  9194
4  VS1  8171
5 VVS2  5066
6 VVS1  3655
7   IF  1790
8   I1   741

在这种情况下,我可能想保留 SI1、VS2 和 SI2,并将其余部分重命名为“clarity_other”。

我该怎么做?有开箱即用的功能吗?我假设这是一个常见的转换,例如在这种情况下,我正在创建虚拟变量并希望在某些功能中合并级别的长尾。

标签: r

解决方案


您可以使用forcats::fct_lump_n()仅保留 n 个最频繁的组并折叠其余组:

library(forcats)
library(dplyr)
library(ggplot2)

diamonds %>% 
  mutate(lumped = fct_lump_n(clarity, 3, other_level = "clarity_other")) %>%
  count(lumped)

# A tibble: 4 x 2
  lumped            n
  <ord>         <int>
1 SI2            9194
2 SI1           13065
3 VS2           12258
4 clarity_other 19423

推荐阅读