You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用tidyverse合并观测数低于阈值的因子水平?

基于观测数合并因子水平的tidyverse实现

可以用tidyverse生态中forcats包的fct_lump_min()函数快速实现需求,它专门用于合并观测数低于指定阈值的因子水平,支持自定义阈值参数。

完整代码示例

library(tidyverse)

# 构造示例数据
df <- tibble(
  animal = factor(c("cat", "cat", "cat", "dog", "dog", "hamster", "goldfish"))
)

# 合并观测数少于2的水平为"other"
df <- df %>%
  mutate(animal2 = fct_lump_min(animal, min = 2, other_level = "other"))

# 查看结果
df

输出结果

# A tibble: 7 × 2
  animal   animal2
  <fct>    <fct>  
1 cat      cat    
2 cat      cat    
3 cat      cat    
4 dog      dog    
5 dog      dog    
6 hamster  other  
7 goldfish other  

参数说明

  • min = 2:自定义阈值,函数会自动合并观测数小于等于该值的因子水平。如果需要合并观测数少于5的组,直接将参数改为min = 5即可
  • other_level = "other":指定合并后的新水平名称,可根据需求修改

原理说明

fct_lump_min()会自动统计每个因子水平的观测数,保留观测数≥阈值的水平,其余全部合并为指定的新水平,无需手动计数和匹配,完全贴合tidyverse的简洁高效风格。

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 08:45:48