01 / 21

Simulation &
Variability in R

Learn to generate simulated data, summarize results, and interpret variability using R programming: from random sampling to understanding the spread of outcomes.

R Programming Statistics

What Is Simulation?

A simulation uses a computer to mimic a random process many times. Instead of collecting real-world data (which can be expensive or slow), we generate synthetic outcomes governed by known probability rules and study the patterns that emerge.

Random Process
Any process whose outcome is uncertain: a coin flip, dice roll, or patient recovery time.
Replicate
One run of the simulation. We repeat many replicates (e.g., 10,000) to see the full range of outcomes.
Summary
After simulating, we compute statistics like the mean, SD, or proportion to describe the distribution.

Why Simulate in R?

R is built for statistical computing. Its random-number functions let you model real-world uncertainty in a single line of code. Simulation helps you:

1
Explore probability without formulas: see how likely an event is by counting occurrences.
2
Understand variability: observe how results change from sample to sample.
3
Check mathematical answers: verify a formula by comparing it to simulated estimates.
4
Build intuition for sampling distributions, confidence intervals, and hypothesis tests.

Core R Functions for Simulation

R provides a family of functions for generating random data. The most important ones:

sample()
Draw items from a vector with or without replacement. Great for coins, dice, and categorical outcomes.
rnorm()
Generate random values from a normal distribution with a given \(\mu\) and \(\sigma\).
replicate()
Repeat an expression many times and collect the results into a vector: the heart of simulation loops.

What Is Variability?

Variability measures how spread out a set of values is. Two simulations can have the same average but very different spreads. Understanding variability tells us how reliable our estimate is.

Value Density Low variability High variability mean

Measuring Variability in R

R gives us several functions to quantify spread. The three most common measures:

sd(x)
Standard deviation: the average distance of each value from the mean. \( s = \sqrt{\frac{1}{n-1}\sum(x_i - \bar{x})^2} \)
var(x)
Variance: the square of the standard deviation. \( s^2 \). Useful in formulas but harder to interpret directly.
IQR(x)
Interquartile range: \( Q_3 - Q_1 \). Robust to outliers: measures the spread of the middle 50%.

The Law of Large Numbers

As the number of simulation replicates \(n\) increases, the sample mean \(\bar{x}\) converges to the true population mean \(\mu\). This is why more replicates = more reliable estimates.

Number of replicates (n) Sample mean
\(\mu\)
10 100 1,000 10,000

Sample vs Population

Simulation helps us understand the distinction between a single sample and the population it came from. Each simulation run is like drawing one sample: the results will vary.

Sample Population
Mean symbol \( \bar{x} \) \( \mu \)
SD symbol \( s \) \( \sigma \)
Size Finite (e.g., \( n = 30 \)) Often infinite or very large
Variability Changes each draw Fixed (unknown)
R function sample(), rnorm() The model parameters you set

How to Run a Simulation

Follow these five steps every time you build a simulation in R:

1
Set the seed: call set.seed() for reproducibility.
2
Define one trial: write the code for a single random outcome (e.g., flip 10 coins, compute proportion of heads).
3
Replicate: use replicate(n, expr) to repeat the trial \(n\) times (e.g., 10,000).
4
Summarize: compute mean(), sd(), or quantile() on the results vector.
5
Visualize: use hist() to see the simulated distribution and check its shape.

Example 1: Coin Flip Simulation

Question: If you flip a fair coin 10 times, what proportion of heads do you get? Repeat 10,000 times and study the distribution.

set.seed(42) # One trial: flip 10 coins, get proportion of heads one_trial <- function() { flips <- sample(c("H", "T"), 10, replace = TRUE) mean(flips == "H") } # Replicate 10,000 times results <- replicate(10000, one_trial()) mean(results) # ≈ 0.50 sd(results) # ≈ 0.16

Coin Flip: Distribution of Results

Proportion of Heads Frequency 0.0 0.2 0.4 0.5 0.6 0.8 1.0 mean = 0.50

Example 2: Normal Sampling

Question: A machine fills bottles with a mean of \(\mu = 500\) mL and \(\sigma = 5\) mL. Simulate 10,000 samples of size \(n = 25\) and examine the distribution of sample means.

set.seed(123) sim_means <- replicate(10000, { samp <- rnorm(25, mean = 500, sd = 5) mean(samp) }) mean(sim_means) # ≈ 500 sd(sim_means) # ≈ 1.0

Example 3: Effect of Sample Size

How does increasing \(n\) change the spread of sample means? Let us simulate with \(n = 5\), \(n = 30\), and \(n = 100\) from the same population (\(\mu = 50\), \(\sigma = 10\)).

Sample Mean
\(\mu = 50\)
\(n = 5\)
\(n = 30\)
\(n = 100\)

The Standard Error Formula

The variability of the sample mean is measured by the standard error:

\(\sigma\)
Population standard deviation: measures how spread out individual observations are.
\(n\)
Sample size: the number of observations in each sample. Appears under a square root.
SE
Standard error: the standard deviation of the sample mean across repeated samples.

Common Mistakes

✕ Confusing SD and SE
SD measures spread of individual values. SE measures spread of the sample mean. They are not interchangeable.
✕ Too Few Replicates
Running only 100 replicates gives a noisy estimate. Use at least 10,000 for stable results.
✕ Forgetting set.seed()
Without a seed, results change each run. This makes debugging and sharing impossible.

Summary of Key Concepts

Concept R Function Interpretation
Generate random data sample(), rnorm() Creates one trial of the simulation
Repeat many trials replicate(n, expr) Builds a distribution of outcomes
Center of distribution mean() Estimate of the distribution's center (e.g., \(\mu\))
Spread of distribution sd(), var() Measures variability of outcomes
Standard error \(\sigma / \sqrt{n}\) Variability of the sample mean
Visualize hist() Shows shape, center, spread

Question 1 of 5

You run replicate(10000, mean(rnorm(50, 100, 15))). What does the sd() of the resulting vector estimate?

Question 2 of 5

Which R function would you use to simulate rolling a six-sided die 20 times?

Question 3 of 5

A simulation of 10,000 sample means has \(\text{SD} = 3.2\). If you quadruple the sample size \(n\) used in each trial, the new SD of sample means would be approximately:

Question 4 of 5

Why is calling set.seed() important before running a simulation in R?

Question 5 of 5

You simulate 10,000 proportions of heads from flipping a fair coin \(n = 100\) times. The resulting histogram will be approximately: