在建模之前减少因子水平的数量 [英] Reducing number of factor levels before modelling

查看:82
本文介绍了在建模之前减少因子水平的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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

这篇关于在建模之前减少因子水平的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆