01 / 20

Random Sampling
in R

Learn to generate random samples using rnorm, runif, and sample: the building blocks of simulation and statistical computing.

R Programming

What is Random Sampling?

Random sampling means drawing values from a probability distribution or a finite set so that each draw is governed by chance. In R, three core functions handle the most common scenarios:

rnorm()
Draws from the normal (Gaussian) distribution: \( \mathcal{N}(\mu, \sigma^2) \)
runif()
Draws from the continuous uniform distribution: \( \text{Uniform}(a, b) \)
sample()
Draws from a discrete set of values, with or without replacement

Why Random Sampling Matters

Every simulation, bootstrap, permutation test, and Monte Carlo method depends on the ability to generate random data. Without it, modern statistics would be impossible.

1
Simulation: Model real-world processes (e.g., stock prices, weather) by sampling thousands of scenarios.
2
Bootstrapping: Estimate confidence intervals by resampling observed data with replacement.
3
Hypothesis testing: Generate null distributions using permutation and randomization methods.

rnorm(): The Normal Distribution

x density -2 -1 0 1 2 μ σ

runif(): The Uniform Distribution

x density 0 0.5 1 1/(b-a) a b

sample(): Discrete Sampling

Population 1 2 3 4 5 6 7 8 sample() Sample 3 7 1

Continuous vs Discrete Sampling

Continuous Discrete
Functions rnorm(), runif() sample()
Output type Numeric (decimals) Elements from a set
Values Infinite possibilities in range Finite set of choices
Example rnorm(5) → 0.32, -1.07... sample(1:6, 2) → 4, 1
Use case Measurements, probabilities Dice, cards, survey picks

Reproducibility with set.seed()

R's random number generator is actually pseudo-random: it uses an algorithm seeded by an initial value. Setting the seed guarantees the same sequence every time.

set.seed(42) rnorm(3) # [1] 1.3710 -0.5647 0.3631 set.seed(42) # Reset the seed rnorm(3) # [1] 1.3710 -0.5647 0.3631 ← same!

How to Generate Random Samples

1
Choose your distribution. Normal for bell-shaped data, uniform for equal-chance ranges, sample for finite sets.
2
Set the seed. Call set.seed() with any integer for reproducibility.
3
Specify parameters. For rnorm(): \( n \), \( \mu \), \( \sigma \). For runif(): \( n \), min, max. For sample(): vector, size, replace.
4
Store the result. Assign to a variable: x <- rnorm(100).
5
Verify. Use hist(x), mean(x), or summary(x) to check the output.

Example 1: Simulating Test Scores

Suppose test scores follow \( \mathcal{N}(75, 10^2) \). Generate 1000 scores and find the proportion above 90.

set.seed(123) scores <- rnorm(1000, mean = 75, sd = 10) # Proportion scoring above 90 mean(scores > 90) # [1] 0.065 # Theoretical: P(X > 90) 1 - pnorm(90, mean = 75, sd = 10) # [1] 0.0668

Example 2: Estimating \( \pi \) with runif()

Generate random points in a unit square and count how many fall inside the quarter-circle of radius 1. The ratio estimates \( \pi / 4 \).

set.seed(99) n <- 10000 x <- runif(n, 0, 1) y <- runif(n, 0, 1) inside <- (x^2 + y^2) <= 1 pi_est <- 4 * mean(inside) pi_est # [1] 3.1284

Example 3: Simulating Dice Rolls

Roll two dice 5000 times and estimate \( P(\text{sum} = 7) \). The theoretical answer is \( \frac{6}{36} = \frac{1}{6} \approx 0.1667 \).

set.seed(7) die1 <- sample(1:6, 5000, replace = TRUE) die2 <- sample(1:6, 5000, replace = TRUE) sums <- die1 + die2 mean(sums == 7) # [1] 0.1674

With vs Without Replacement

replace = TRUE
Each draw goes back into the pool. Items can repeat. Use for: dice rolls, coin flips, bootstrapping.
replace = FALSE
Each drawn item is removed. Items cannot repeat. Use for: card dealing, lottery draws, random assignment.
# With replacement: repeats possible sample(1:5, 5, replace = TRUE) # [1] 3 1 3 5 2 # Without replacement: a permutation sample(1:5, 5, replace = FALSE) # [1] 4 2 5 1 3

Weighted Sampling with prob

The prob argument lets you assign unequal probabilities to each element. R automatically normalizes the weights so they sum to 1.

# Loaded die: 6 appears 50% of the time set.seed(10) rolls <- sample( 1:6, size = 1000, replace = TRUE, prob = c(0.1, 0.1, 0.1, 0.1, 0.1, 0.5) ) table(rolls) # rolls # 1 2 3 4 5 6 # 99 105 86 108 96 506

Common Mistakes

✕ Forgetting set.seed()
Results change every run, making debugging and grading impossible. Always set a seed for reproducibility.
✕ Wrong replace argument
Using replace = FALSE when you need independent draws (like dice), or TRUE when items should not repeat.
✕ Confusing sd with variance
rnorm() takes standard deviation (\( \sigma \)), not variance (\( \sigma^2 \)). If given \( \sigma^2 = 25 \), pass sd = 5.

Summary: Three Sampling Functions

rnorm() runif() sample()
Distribution Normal \( \mathcal{N}(\mu, \sigma^2) \) Uniform \( [a, b] \) Discrete (any vector)
Key params mean, sd min, max x, size, replace
Output Numeric (continuous) Numeric (continuous) Same type as input
Default \( \mu=0,\;\sigma=1 \) \( a=0,\;b=1 \) Without replacement
Typical use Measurement simulation Monte Carlo, random coords Resampling, permutations

Question 1 of 5

Which function would you use to generate 50 random values from a normal distribution with \( \mu = 100 \) and \( \sigma = 15 \)?

Question 2 of 5

What does set.seed(42) do?

Question 3 of 5

You want to simulate drawing 5 cards from a standard 52-card deck without putting them back. Which call is correct?

Question 4 of 5

What is the range of possible values produced by runif(100, min = 3, max = 8)?

Question 5 of 5

Running sample(1:3, size = 5) without specifying replace will: