我有一个数据框架,按月列出库存、到货数量和预期消费。
我需要计算每月需要购买的数量,以维持我的股票高于一定的安全库存每月。
例如:我有3个单位的库存,4个到达第一个月,预计消费0。因此,这个月我不需要购买任何单位,剩下的是3+4-0=7。
这意味着下个月我将从7开始,假设消费是7,到达1单位。因此,我将在3低于我的安全库存4,所以我需要规划一个购买3单位的月份。
第三个月我开始我的4单位的安全库存,1单位到达,消费5,所以我在0,所以我需要程序购买4,以补充我的安全库存。
举个例子,我需要复制以下内容,其中“要购买”是我需要计算的
df <- data.frame(type = c("a","a","a","a","a"),
date = as.Date(c("2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01", "2020-05-01")),
stock= c(3,0,0,0,0),
arriving = c(4,1,1,3,2),
consumption = c(0,7,5,5,3),
safety_stock = c(4,4,4,4,4),
to_purchase= c(0,3,4,2,1))发布于 2020-07-23 01:34:54
假设这些库存是不易腐烂的,那么每个月的初始stock应该等于你上个月留下的数量。
每个月的to_purchase方程应该是
to_purchase = safety_stock - (stock - consumption + arriving),
这基本上是需求减去可用供给。
library(tidyverse)
df <- data.frame(
type = c("a","a","a","a","a"),
date = as.Date(c("2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01", "2020-05-01")),
stock = c(3,7,4,4,4),
arriving = c(4,1,1,3,2),
consumption = c(0,7,5,5,3),
safety_stock = c(4,4,4,4,4)
) %>%
mutate(
to_purchase = safety_stock - (stock - consumption + arriving), # purchase equation
to_purchase = ifelse(to_purchase < 0, 0, to_purchase) # if negative, change value to zero
)然而,这方面的一个问题是,如果您试图计算您需要购买的金额(to_purchase),您可能还需要计算前一个月(stock)的剩余金额。因此,您的代码还应该包括每个月的初始stock的计算。
df <- data.frame(
type = c("a","a","a","a","a"),
date = as.Date(c("2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01", "2020-05-01")),
stock = c(3,NA,NA,NA,NA),
arriving = c(4,1,1,3,2),
consumption = c(0,7,5,5,3),
safety_stock = c(4,4,4,4,4),
to_purchase = NA
)
for(i in 2:nrow(df)){
# determine if you need to purchase anything from the previous month
h = i-1
df$to_purchase[h] = df$safety_stock[h] - (df$stock[h] - df$consumption[h] + df$arriving[h])
df$to_purchase[h] = ifelse(df$to_purchase[h] < 0, 0, df$to_purchase[h])
# determine initial stock of the current month
df$stock[i] = df$stock[h] + df$arriving[h] - df$consumption[h] + df$to_purchase[h]
# determine if you need to purchase anything for the current month
df$to_purchase[i] = df$safety_stock[i] - (df$stock[i] - df$consumption[i] + df$arriving[i])
df$to_purchase[i] = ifelse(df$to_purchase[i] < 0, 0, df$to_purchase[i])
}
df
#> type date stock arriving consumption safety_stock to_purchase
#> 1 a 2020-01-01 3 4 0 4 0
#> 2 a 2020-02-01 7 1 7 4 3
#> 3 a 2020-03-01 4 1 5 4 4
#> 4 a 2020-04-01 4 3 5 4 2
#> 5 a 2020-05-01 4 2 3 4 1https://stackoverflow.com/questions/63021616
复制相似问题