如何用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
相关产品推荐
相关产品推荐

