Issues with Monte Carlo Simulation in R

Viewed 22

This is my code, but I am facing some issues. This line: results <- MonteCarlo(model, n = 10000), gives me the following error:

Error in MonteCarlo(model, n = 10000) : 
  argument 2 matches multiple formal arguments

This is the whole code. Can anyone see where I have made a mistake?

install.packages("MonteCarlo")
library(MonteCarlo)


year1.price <- 1800 
year2.price <- c(-250, 200, 500) 
year3.price <- c(-250, 200, 500) 
year4.price <- c(-250, 200, 500) 
year5.price <- c(-250, 200, 500) 

output.distribution <- c(100, 1000, 1800) 
annual.change <- c(-0.15, 0.3, 0.7) 
fixed.costs <- c(500000, 750000, 1000000) 
legal.costs <- c(500000, 750000, 1000000) 

 
model <- function() { 
  year1.revenue <- year1.price * output.distribution[2] 
  year2.revenue <- year2.price[sample(1:3, 1)] * (output.distribution[2] + output.distribution[2] * annual.change[sample(1:3, 1)]) 
  year3.revenue <- year3.price[sample(1:3, 1)] * (output.distribution[2] + output.distribution[2] * annual.change[sample(1:3, 1)]) 
  year4.revenue <- year4.price[sample(1:3, 1)] * (output.distribution[2] + output.distribution[2] * annual.change[sample(1:3, 1)]) 
  year5.revenue <- year5.price[sample(1:3, 1)] * (output.distribution[2] + output.distribution[2] * annual.change[sample(1:3, 1)]) 
  
  total.revenue <- year1.revenue + year2.revenue + year3.revenue + year4.revenue + year5.revenue 
  total.costs <- fixed.costs[2] + legal.costs[sample(1:3, 1)] 
  net.revenue <- total.revenue - total.costs 
  
  return(net.revenue) 
} 

results <- MonteCarlo(model, n = 10000)


summary(results)
1 Answers

The specific error you are getting is because MonteCarlo does not have an argument called n. The argument you are looking for is called nrep. However, fixing this will give you another error saying that your list of parameters is missing. The reason for this is simply that you are using the wrong function here.

If I understand you correctly, you are trying to get 10000 repetitions of the function model. However, MonteCarlo is designed to be used in more complex situations where you want replicates of a function that accepts multiple parameters which may vary over the replicates. Your function does not take any parameters, so MonteCarlo throws an error, and in any case you can get the result you are looking for simply by using the base R function replicate, which will do just what you are looking for

results <- replicate(10000, model())

So for example:

length(results)
#> [1] 10000

mean(results)
#> [1] 1075661

hist(results)

enter image description here

Related