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

使用base::cumsum实现分组内固定分母累加计算,生成目标should列

修正方案

核心逻辑优化:观察目标should列的计算规则,可将同一行公共的分母「当前行th」从累加运算中提取出来,先按组累加group^seq * th的分子项,再统一除以当前行的th即可得到正确结果,无需复杂的滚动窗口计算。

修正后完整代码

demo <- data.frame(
  th = c(20.1,24.1,26.1,1.1,2.1,4.1),
  seq = c(1:3,1:3),
  group = c(rep(10,3), rep(20,3))
)

library(dplyr)
library(magrittr)

demo %>% 
  group_by(group) %>%
  mutate(
    # 先累加分子部分:group^seq * th的累计和
    temp_cumsum = cumsum(group^seq * th),
    # 统一除以当前行的th得到正确的cumsum_a
    cumsum_a = temp_cumsum / th
  ) %>% 
  ungroup() %>% 
  # 移除临时列,和原有测试列对比
  select(-temp_cumsum) %>% 
  mutate(
    cumsum_m = c(
      10^1*20.1/20.1,
      10^1*20.1/20.1 + 10^2*24.1/24.1,
      10^1*20.1/20.1 + 10^2*24.1/24.1 + 10^3*26.1/26.1,
      20^1*1.1/1.1,
      20^1*1.1/1.1 + 20^2*2.1/2.1,
      20^1*1.1/1.1 + 20^2*2.1/2.1 + 20^3*4.1/4.1
    ),
    should = c(
      10^1*20.1/20.1,
      10^1*20.1/24.1 + 10^2*24.1/24.1,
      10^1*20.1/26.1 + 10^2*24.1/26.1 + 10^3*26.1/26.1,
      20^1*1.1/1.1,
      20^1*1.1/2.1 + 20^2*2.1/2.1,
      20^1*1.1/4.1 + 20^2*2.1/4.1 + 20^3*4.1/4.1
    )
  )

结果验证

运行后输出如下,可见cumsum_a和should列完全匹配:

# A tibble: 6 × 6
     th   seq group cumsum_a cumsum_m should
  <dbl> <int> <dbl>    <dbl>    <dbl>  <dbl>
1  20.1     1    10      10        10    10 
2  24.1     2    10     108.      110   108.
3  26.1     3    10    1100.     1110  1100.
4   1.1     1    20      20        20    20 
5   2.1     2    20     410.      420   410.
6   4.1     3    20    8210.     8420  8210.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:12:05