1

I am running a simulation model in R. 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? 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])
}
gchoi98
  • 29
  • 1
  • 5

2 Answers2

2

You can use replicate to repeat the simulation for n times. rowMeans would calculate average of profit at each 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()))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

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.

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
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66