我有一个2600级的因子,我想在建模之前将其降低到〜10
I have a factor with 2600 levels and I want to reduce it to ~10 before modelling
我想我可以通过一个操作来做到这一点,如果列出的因子少于x次,应将其放入称为其他的存储桶中。
I thought I could do this with an operation that says "if a factor is listed fewer than x times, it should be placed into a bucket called "other"
以下是一些示例数据:
df <- data.frame(colour=c("blue","blue","blue","green","green","orange","grey"))这是我希望得到的输出:
And this is the output I am hoping for:
colour 1 blue 2 blue 3 blue 4 green 5 green 6 other 7 other我尝试了以下操作:
df %>% mutate(colour = ifelse(count(colour) < 2, 'other', colour))
mutate_impl(.data,点)中的错误:评估错误:否
Error in mutate_impl(.data, dots) : Evaluation error: no applicable method for 'groups' applied to an object of class "factor".
推荐答案
tidyverse中实际上有一个名为 forcats 的不错的程序包,它可以帮助处理因素。您可以使用 fct_lump ,它确实满足您的需求:
There is actually a nice package in the tidyverse called forcats which helps in dealing with factors. You can use fct_lump, which does exactly what you need:
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更多推荐
在建模之前减少因子水平的数量
发布评论