在建模之前减少因子水平的数量

编程入门 行业动态 更新时间:2024-10-07 12:27:04
本文介绍了在建模之前减少因子水平的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

在建模之前减少因子水平的数量

本文发布于:2023-11-29 09:12:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645968.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:建模   因子   数量   水平

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!