简体   繁体   English

模拟 Model 和 R 中的 For 循环

[英]Simulation Model and For Loop in R

I am running a simulation model in R.我正在 R 中运行模拟 model。 How do I make the for loop multiply all capacity values and create a list of the average of each profit at the capacity level?如何使 for 循环乘以所有容量值并创建容量级别每个利润平均值的列表? Thank you!谢谢!

BuildCost <- 16.00
SellPrice <- 3.70
VariableCost <- 0.20
OperationCost <- 0.40
Capacity <- c(30000,35000,40000,45000,50000,55000,60000)
Years <- 10

Profs <- c()
for (i in 1:1000){
  Demand <- rnorm(1,50000,12000)
  FixedCost <- Capacity*BuildCost
  AnnualProfit <- Demand * SellPrice
  ProductionCost <- Capacity*VariableCost
  OperationalCost <- Capacity*OperationCost
  TotalProfit <- Years*AnnualProfit-FixedCost-Years*(ProductionCost+OperationalCost)
  Profs[i]<- TotalProfit
  x <- mean(Profs[i])
}

You can use replicate to repeat the simulation for n times.您可以使用replicate重复模拟n次。 rowMeans would calculate average of profit at each Capacity . rowMeans将计算每个Capacity的平均利润。

simulation <- function() {
  Demand <- rnorm(1,50000,12000)
  FixedCost <- Capacity*BuildCost
  AnnualProfit <- Demand * SellPrice
  ProductionCost <- Capacity*VariableCost
  OperationalCost <- Capacity*OperationCost
  Years*AnnualProfit-FixedCost-Years*(ProductionCost+OperationalCost)
}

rowMeans(replicate(100, simulation()))

Create a results matrix with the right dimensions and populate it in the loop.创建具有正确尺寸的结果矩阵并将其填充到循环中。 The final result is exactly the same as the result of Ronak Shah's code if the RNG seed is set to the same value before the simulations are run.如果在运行模拟之前将 RNG 种子设置为相同的值,则最终结果与Ronak Shah代码的结果完全相同。

set.seed(2021)
n <- 1000
Profs <- matrix(nrow = n, ncol = length(Capacity))
Demand <- rnorm(n, 50000, 12000)

for (i in seq_len(n)){
  FixedCost <- Capacity*BuildCost
  AnnualProfit <- Demand[i] * SellPrice
  ProductionCost <- Capacity*VariableCost
  OperationalCost <- Capacity*OperationCost
  TotalProfit <- Years*(AnnualProfit - ProductionCost - OperationalCost) - FixedCost
  Profs[i, ] <- TotalProfit
}

colMeans(Profs)
#[1] 1195661.9 1085661.9  975661.9  865661.9  755661.9  645661.9  535661.9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM