在R中对逐步模拟进行矢量化

在R中对逐步模拟进行矢量化,r,R,我已经在R中编写了一个脚本,其中我正在模拟仓库的进货和出库流程: set.seed(10) #Create dataframe df1 <- data.frame(date = seq(1,20), #Stock in to warehouse on date stockIn = round(10+10*runif(10),0), #Stock out of warehouse o

我已经在R中编写了一个脚本,其中我正在模拟仓库的进货和出库流程:

set.seed(10)

#Create dataframe
df1 <- data.frame(date = seq(1,20),
                  #Stock in to warehouse on date
                  stockIn = round(10+10*runif(10),0),
                  #Stock out of warehouse on date
                  stockOut = round(10+10*runif(10),0))

#The initial inventory level of the warehouse on date 1
initBalance <- 20

#Create a column of NAs which holds the end of day stock level
df1$endStockBalance <- NA

#Loop through each day
for(i in 1:nrow(df1)){
  #If it's the first day, put initBalance into endStockBalance 
  if(i == 1){
    df1[i,4] <- initBalance
  #For other days, take the maximum of the previous day's inventory plus the difference between stock in and stock out, and 0 (we can't have negative stock levels)
  } else {
    df1[i,4] <- max(df1[i-1,4] + df1[i,2] - df1[i,3],0)
  }
}
set.seed(10)
#创建数据帧

df1您基本上可以将循环更改为

cumsum(c(initBalance, df1$stockIn[-1] - df1$stockOut[-1]))
#[1] 20 17 20 21 18 16 18 18 20 16 14 11 14 15 12 10 12 12 14 10
这与运行
for
循环后得到的
endStockBalance
相同

identical(df1$endStockBalance, 
           cumsum(c(initBalance, df1$stockIn[-1] - df1$stockOut[-1])))
#[1] TRUE
如果要为负值指定0,可以使用
pmax

pmax(cumsum(c(initBalance, df1$stockIn[-1] - df1$stockOut[-1])), 0)