我有一个 2600 级的因子,我想在建模之前将其减少到 ~10
我想我可以用一个操作来做到这一点,它说“如果一个因子被列出的次数少于 x 次,它应该被放入一个名为“其他”的桶中
以下是一些示例数据:
df <- data.frame(colour=c("blue","blue","blue","green","green","orange","grey"))
Run Code Online (Sandbox Code Playgroud)
这是我希望的输出:
colour
1 blue
2 blue
3 blue
4 green
5 green
6 other
7 other
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法:
df %>% mutate(colour = ifelse(count(colour) < 2, 'other', colour))
Run Code Online (Sandbox Code Playgroud)
mutate_impl(.data, dots) 中的错误:评估错误:“组”没有适用的方法应用于“因子”类的对象。
实际上在 tidyverse 中有一个很好的包,forcats
它可以帮助处理因素。您可以使用fct_lump
,它完全符合您的需要:
library(tidyverse)
df %>% mutate(colour = fct_lump(colour, n = 2))
#> colour
#> 1 blue
#> 2 blue
#> 3 blue
#> 4 green
#> 5 green
#> 6 Other
#> 7 Other
Run Code Online (Sandbox Code Playgroud)
使用tidyverse
函数,您可以尝试以下操作:
df %>%
group_by(colour) %>%
mutate(cnt = n()) %>%
mutate(grp = if_else(cnt >= 2, as.character(colour), as.character("Other"))) %>%
select(-cnt)
Run Code Online (Sandbox Code Playgroud)
这给出了(这里,阈值为>= 2
)
colour grp
<fct> <chr>
1 blue blue
2 blue blue
3 blue blue
4 green green
5 green green
6 orange Other
7 grey Other
Run Code Online (Sandbox Code Playgroud)