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

基于dplyr、cumsum和lag的分龄库存调度计算问题

用dplyr高效计算跨年龄组库存供需匹配

针对你需要按库存年龄从新到旧计算供需匹配的需求,这里提供一个基于dplyr向量运算的高效方案,完全避免循环,适合处理千万级规模的数据集:

实现代码

library(dplyr)

# 示例数据集
Inventory <- data.frame(
  Age = c(90, 120, 270, 365, Inf),
  Demand = c(0, 5000, 25, 5000, 10),
  Supply = c(4000, 50, 4000, 300, 0)
)

# 核心计算逻辑(实际使用时需添加产品、日期分组:group_by(Product, Date))
Result <- Inventory %>%
  arrange(Age) %>%  # 按库存年龄从新到旧排序
  mutate(
    # 计算累计供应、累计需求,以及到当前组的剩余库存
    cum_supply = cumsum(Supply),
    cum_demand = cumsum(Demand),
    cum_surplus = pmax(cum_supply - cum_demand, 0),
    # 推导各库存字段
    Start = lag(cum_surplus, default = 0),
    In = Supply,
    Out = pmin(Demand, Start + In),
    End = Start + In - Out,
    Short = Demand - Out
  ) %>%
  select(-cum_supply, -cum_demand, -cum_surplus)  # 移除中间计算字段

# 输出结果
Result

结果验证

运行上述代码后,得到的结果与你预期的完全一致:

Age Demand Supply Start   In  Out   End Short
1   90      0   4000     0 4000    0  4000     0
2  120   5000     50  4000   50 4050     0   950
3  270     25   4000     0 4000   25  3975     0
4  365   5000    300  3975  300 4275     0   725
5  Inf     10      0     0    0    0     0    10

逻辑说明

  1. 排序与分组:先按Age从小到大排序(确保从新库存到旧库存处理),实际场景中需先按Product和Date分组,再进行排序计算。
  2. 累计计算:用cumsum计算累计供应和累计需求,cum_surplus记录到当前组为止的剩余可用库存,这个值的滞后项(lag(cum_surplus))就是下一组的Start(上一期的End)。
  3. 字段推导:基于累计值直接推导Out、End、Short,全程使用向量运算,效率远高于循环,能轻松应对千万级行数的数据集。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 18:16:20