首页 > 解决方案 > 在 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

标签: rdplyrtidyverseforcats

解决方案


一种选择可能是使用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

推荐阅读