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

按组计算取整平均值,且组总和与原组总和相等

按组均分数值并保证总和一致

原始数据

library(dplyr)

Data <- tibble(
  ID = c("Code001", "Code001","Code001","Code002","Code002","Code002","Code002","Code002","Code003","Code003","Code003","Code003"),
  Value = c(107,107,107,346,346,346,346,346,123,123,123,123)
)

需求说明

按ID分组,将每组的Value总和(因每组内Value值相同,总和为Value × 行数)均分到每行,结果需取整且分组后的Prop_Value总和必须与原组Value总和完全相等。

无效方案示例

直接对平均值取整的方式会导致总和偏差,无法满足需求:

Data %>%
  add_count(ID) %>%
  group_by(ID) %>%
  mutate(Prop_Value_1 = Value/n,
         Prop_Value_2 = round(Value/n))

比如Code001组,107/3≈35.666,round后每行都是36,总和为108,与原总和107不符;Code002组346/5=69.2,round后每行都是69,总和345,与原总和346不符。

可行解决方案

通过计算基础值和余数,给前若干行加1来保证总和一致:

Data %>%
  group_by(ID) %>%
  mutate(
    n = n(),
    total = first(Value) * n,
    base_val = total %/% n,
    remainder = total %% n,
    Prop_Value = ifelse(row_number() <= remainder, base_val + 1, base_val)
  ) %>%
  ungroup() %>%
  select(-n, -total, -base_val, -remainder)

运行后得到的Prop_Value列完全符合预期:

IDValueProp_Value
Code00110735
Code00110736
Code00110736
Code00234669
Code00234669
Code00234669
Code00234669
Code00234670
Code00312330
Code00312331
Code00312331
Code00312331

每组总和均与原Value总和一致:

  • Code001:35+36+36=107
  • Code002:69×4+70=346
  • Code003:30+31×3=123

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:50:46