【问题标题】:tidyverse grouping combining small groups into "other"tidyverse 分组将小组组合成“其他”
【发布时间】:2019-05-21 22:02:33
【问题描述】:

假设我要汇总某个数据框列:

> starwars %>% count(eye_color)
# A tibble: 15 x 2
   eye_color         n
   <chr>         <int>
 1 black            10
 2 blue             19
 3 blue-gray         1
 4 brown            21
 5 dark              1
 6 gold              1
 7 green, yellow     1
 8 hazel             3
 9 orange            8
10 pink              1
11 red               5
12 red, blue         1
13 unknown           3
14 white             1
15 yellow           11

有很多小类别,例如“蓝灰色”或“粉红色”。我想将它们全部合并到“其他”中。有一个多步骤的过程来做到这一点:

starwars %>%
add_count(eye_color) %>%
mutate(eye_color = if_else(n < 5, "other", eye_color)) %>%
count(eye_color)

还有一种方法可以使用单个命令来完成。以前在哪里看到过这个技巧,现在找不到了。

【问题讨论】:

  • 你在想forcats::fct_lump吗?

标签: r dplyr tidyverse


【解决方案1】:

写下@Jordan 的建议:

更新:使用 Camille 的修复:

starwars %>%  mutate(eye_color_grp = as.factor(eye_color) %>%
                       forcats::fct_lump_min(min = 5, other_level = "Other")) %>%
  count(eye_color_grp, sort = TRUE) 

链接:https://forcats.tidyverse.org/reference/fct_lump.html

【讨论】:

  • 查看该函数的文档:fct_lumpn = 5 保留 5 个最常出现的级别,而 fct_lump_minmin = 5 保留至少出现 5 次的级别。后者匹配 OP 的 if_else 声明。
  • 其实可以跳过as.factor()
猜你喜欢
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
相关资源
最近更新 更多