r - 开箱即用的功能将关卡的长尾放置在一个功能中作为“其他”?
问题描述
假设我在 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”。
我该怎么做?有开箱即用的功能吗?我假设这是一个常见的转换,例如在这种情况下,我正在创建虚拟变量并希望在某些功能中合并级别的长尾。
解决方案
您可以使用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
推荐阅读
- scala - 两个数据集连接后如何自动触发推断数据集?
- javascript - Amcharts4 从前端改变目的
- typescript - 添加交叉点会导致奇怪的错误
- flutter - 地区不支持错误,Apple Pay,国家:印度,Flutter
- python - 使用python列出来自Windows任务调度程序的所有任务
- html - 显示有什么问题:我的代码中的 inline-block
- typescript - TypeScript 错误:类型 '{ user: any; 上不存在属性 'length' 密码:任何;}'
- mongodb - 如何将限制传递给 Mongoose db.collection.deleteMany
- ios - 为什么我的文件提供程序在文件应用程序中的位置是灰色的(非活动的)
- c++ - 调用从 Rust 接收命令行参数的 C++ 函数的问题