r - 在 R 中有没有办法结合函数 slice_max (dplyr) 和 fct_other(forcats)?
问题描述
我正在尝试将 dplyr 中的 slice_max 函数和 forcats 中的 fct_other 函数结合起来,以基于数字变量获得数据帧的前 n 个切片,但我不想丢失非前 n 个因素。我希望将这些其他因素指定为“其他”,以便在需要时对其进行总结或计数。
例如,使用与此类似的数据框:
df <- data.frame(acron = c("AA", "BB", "CC", "DD", "EE", "FF", "GG"), value = c(6, 4, 1, 10, 3, 1, 1))
如果我想要前 3 个主题的“价值”,我可以使用下面的代码:
df %>%
slice_max(value, n = 3)
得到下一个结果:
acron 值
DD 10
AA 6
BB 4
但我想指定删除“acron”的因素“其他”类似于使用来自 forcats 的函数 fct_other 获得的结果。我试过这段代码,但它不起作用:
df %>%
mutate(acron = fct_other(acron, keep = slice_max(value, n = 3), other_level = "Others"))
有什么建议可以得到这样的东西吗?:
acron 值
DD 10
AA 6
BB 4
其他 3
其他 1
其他 1
其他 1
甚至像这样:
acron 值
DD 10
AA 6
BB 4
其他 6
解决方案
一种选择可能是使用fct_lump_n()
:
df %>%
mutate(acron = fct_lump_n(acron, n = 3, w = value))
acron value
1 AA 6
2 BB 4
3 Other 1
4 DD 10
5 Other 3
6 Other 1
7 Other 1
推荐阅读
- typescript - 基于接口实现类方法
- android - 我的导航视图未显示我的菜单项
- c - 在c中使用while循环查找a1z,b2y,c3x,...,...,....,nnn的斐波那契数列的程序?
- python - 如何在 cloudant-python 中选择特定字段进行查询?
- python - 在 Dask 中处理多个 csv
- php - 在 MySQL 中对通过 UNION 连接的 SUM 进行求和,并在 PHP 中使用 ECHO 显示
- python - 无法构造反向牛顿多项式
- python - 缓存烧瓶登录 current_user.is_authenticated
- javascript - 在 PWA 中保持计时器运行的最佳实践
- tensorflow - 我当前在物理空间上保存的微调 BERT 模型需要 7GB 空间。模型占用这么大的空间是正常的吗?