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

如何在R语言中将出现次数不足5次的类别归为“other”分组?

R: Group Rare Categories into "other" While Retaining Frequent Ones

首先先复现你的数据集:

df <- data.frame(Id = seq(1,12), col1 = c(rep('A',5),'B','B','C','D',rep('A',3)))

你的需求是新增col2列:保留出现次数≥5的类别(这里只有"A"),其余类别统一归为"other"。下面是两种实用的实现方法:

方法1:Base R 实现

这种方法不需要额外安装工具包,适合轻量需求:

# 统计col1中每个类别的出现频率
category_freq <- table(df$col1)
# 筛选出需要保留的类别(出现次数≥5)
keep_categories <- names(category_freq[category_freq >= 5])

# 新增col2列
df$col2 <- ifelse(df$col1 %in% keep_categories, df$col1, "other")

方法2:Tidyverse (dplyr) 实现

如果你习惯使用数据管道风格的代码,dplyr的方法更直观:

library(dplyr)

df <- df %>%
  # 为每个col1的类别添加出现次数列n
  add_count(col1) %>%
  # 根据次数判断生成col2
  mutate(col2 = case_when(
    n >= 5 ~ col1,
    TRUE ~ "other"
  )) %>%
  # 移除临时的次数列n
  select(-n)

最终结果

执行任意一种方法后,你都会得到期望的数据集:

print(df)
#    Id col1  col2
# 1   1    A     A
# 2   2    A     A
# 3   3    A     A
# 4   4    A     A
# 5   5    A     A
# 6   6    B other
# 7   7    B other
# 8   8    C other
# 9   9    D other
# 10 10    A     A
# 11 11    A     A
# 12 12    A     A

内容的提问来源于stack exchange,提问作者Marwah Al-kaabi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 05:27:39