I simulate a warehouse in R, where supplies (o.in) arrive with random lead times and demand (d) is served. The stock level (stockHistory) is calculated based on the difference between supply and demand.
for(i in 1:periods){
stockHistory[i] = stockHistory[i] - d[i] + o.in[i] # o.in has been determined in previous looping, d is known before loop
openOrders = openOrders - o.in[i]
missing_packages = ceiling((reorderPoint - stockHistory[i] - openOrders)/q) # stockHistory + openOrders are based on o.in and calculated in loop
if (missing_packages > 0 ) {
openOrders = openOrders + missing_packages * q
o.in[leadtimes[i]+i] = o.in[leadtimes[i]+i] + missing_packages * q # leadtimes is known before looping
}
}
How can I avoid the for loop by vectorization? My problem is that I do not know how to handle the
o.in[leadtimes[i]+i] = o.in[leadtimes[i]+i] + missing_packages * q
in a vectorizedd way so that the offset leadtimes[i]+i in the vector is accounted for elementwise in the calculation. I checked diff(), but it doesn't seem apt for my use case.
The second problem is that I cannot determine the right order for the operations since they are based one on another.
Any help would be highly appreciated. Thanks in advance!