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

基于组内中位数的分类:用case_when实现高效分组逻辑

用case_when高效实现分组生成Results列

原始数据集

ID  Quantity    Group     Indicator
1   0.93        Red       1
2   0.17        Red       1
3   0.01        Red       0
4   0.44        Red       1
5   0.01        Red       0
6   0.86        Red       1
7   0.07        Red       1
8   0.02        Red       0   
9   1.00        Red       1
1   0.65        Blue      1
2   0.17        Blue      1
3   0.02        Blue      0
4   0.01        Blue      0
5   0.09        Blue      1
6   0.86        Blue      1
7   0.05        Blue      0
8   0.23        Blue      1
9   0.01        Blue      0

实现代码

使用dplyr包的group_by+mutate+case_when组合,能简洁实现需求:

library(dplyr)

# 构造数据集
df <- tibble(
  ID = c(1:9, 1:9),
  Quantity = c(0.93, 0.17, 0.01, 0.44, 0.01, 0.86, 0.07, 0.02, 1.00,
               0.65, 0.17, 0.02, 0.01, 0.09, 0.86, 0.05, 0.23, 0.01),
  Group = rep(c("Red", "Blue"), each = 9),
  Indicator = c(1,1,0,1,0,1,1,0,1,
                1,1,0,0,1,1,0,1,0)
)

# 生成Results列
df_result <- df %>%
  group_by(Group) %>%
  mutate(
    # 计算组内Indicator=1的Quantity中位数
    med_val = median(Quantity[Indicator == 1], na.rm = TRUE),
    # 按规则赋值
    Results = case_when(
      Indicator == 0 ~ 1,
      Indicator == 1 & Quantity >= med_val ~ 3,
      TRUE ~ 2  # 剩余Indicator=1且Quantity<=中位数的情况
    )
  ) %>%
  ungroup() %>%
  select(-med_val)  # 移除临时计算列

# 输出完整结果
print(df_result, n = 18)

代码说明

  1. 分组计算中位数:按Group分组后,计算每组中Indicator=1对应的Quantity中位数,存为临时列med_val;
  2. case_when多条件匹配:
    • 优先匹配Indicator==0的情况,直接赋值1;
    • 再匹配Indicator==1且Quantity≥中位数的情况,赋值3;
    • 最后用TRUE匹配剩余所有Indicator==1且Quantity≤中位数的情况,赋值2;
  3. 清理临时列:取消分组后移除临时计算的中位数列,得到最终结果。

运行代码后得到的结果与示例完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:42:43