How to Perform Monte Carlo Simulations in R (With Example)

How to Perform Monte Carlo Simulations in R (With Example)
Image by Editor | ChatGPT

Monte Carlo simulations are a way to handle uncertainty. They use random numbers to test many possible outcomes. This helps estimate risks and predict results. The process involves running a model thousands of times. Each time, it uses random inputs to simulate a scenario. Analyzing the results helps you see the range of possible outcomes.

In this article, we’ll explain how to perform these simulations in R.

Define the Problem and Model

Before starting the simulation, you must define the problem clearly. Understand the process and variables involved. Know how the variables are related. For example, we can simulate a business’s profit with uncertain sales, price per unit, and costs.

  • Sales: Normally distributed with a mean of 10,000 and a standard deviation of 2,000
  • Price per unit: Uniformly distributed between $10 and $20
  • Costs: Fixed at $80,000

Profit is calculated as: Profit = (Sales × Price per Unit) – Costs

Generate Random Inputs

In R, random variables are created using functions like rnorm() for normal distributions and runif() for uniform distributions. These functions generate different random values for each simulation. This helps simulate uncertainty by changing the inputs each time.

# Set seed for reproducibility
set.seed(123)

# Number of simulations
n_simulations <- 10000

# Generate random inputs
sales <- rnorm(n_simulations, mean = 10000, sd = 2000)
price_per_unit <- runif(n_simulations, min = 10, max = 20)
fixed_costs <- 80000

Perform the Simulations

With the random samples generated, you can now run the simulations. This involves calculating the profit for each simulation using a vectorized approach.

# Calculate profit for each simulation
profit <- (sales * price_per_unit) - fixed_costs

Analyze the Results

After running the simulations, it’s important to analyze the results to understand the possible range of outcomes. You can do this by calculating summary statistics and visualizing the distribution of results.

Summary Statistics

Use the summary() function to get an overview of the results. It shows the mean, median, and quantiles.

# Summary statistics
summary(profit)

summary

This gives a quick view of the profit distribution. It shows the minimum, 1st quartile, median, mean, 3rd quartile, and maximum.

Visualization

A histogram is an easy way to see how simulated profits are spread out. You can use the hist() function in R to create a histogram of the results.

# Visualize the results
hist(profit, breaks = 50, col = "skyblue", main = "Monte Carlo Simulation: Profit Distribution",
     xlab = "Profit", border = "white")

histogram

This histogram shows how the profits are spread out. It displays how often each range of profit values appears in the simulation.

Advanced Techniques for Monte Carlo Simulations in R

Using data.table for Efficiency

For large simulations, using data.table can make data manipulation faster and more efficient. Here’s how you can use it to store and calculate results:

library(data.table)

# Create a data.table
sim_data <- data.table(sales = rnorm(n_simulations, mean = 10000, sd = 2000),
                       price_per_unit = runif(n_simulations, min = 10, max = 20))

# Add profit calculation
sim_data[, profit := (sales * price_per_unit) - fixed_costs]

# Print the first few rows of the table
head(sim_data)

data.table

Parallel Computing for Faster Simulations

For very large simulations, parallel computing can speed up the process. The parallel or furrr package allows you to run simulations across multiple cores.

Here’s an example using parallel:

library(parallel)

# Number of cores to use
num_cores <- detectCores() - 1

# Calculate simulations to run on each core
sims_per_core <- ceiling(n_simulations / num_cores)

# Function to run a batch of simulations
run_simulation_batch <- function(i) {
  # Generate random data for one batch
  sales <- rnorm(sims_per_core, mean = 10000, sd = 2000)
  price_per_unit <- runif(sims_per_core, min = 10, max = 20)
  profit <- (sales * price_per_unit) - fixed_costs
  
  return(profit)
}

# Run simulation batches in parallel
results_list <- mclapply(1:num_cores, run_simulation_batch, mc.cores = num_cores)

# Combine results from all cores into a single vector
all_results <- unlist(results_list)

# Trim the vector to the desired number of simulations
all_results <- all_results[1:n_simulations]

# Print summary of results
summary(all_results)

parallel_computing

Conclusion

Monte Carlo simulations help to understand and measure uncertainty in complex processes. By defining a model, generating random inputs, and running many simulations, you can assess potential outcomes and their probabilities. R offers tools like rnorm() and runif() for simulating and analyzing results. Advanced techniques like data.table and parallel computing make large simulations more efficient.

Leave a Reply

Your email address will not be published. Required fields are marked *