🎲 The Magic Number Machine: Random Numbers in R
The Story of Randomness
Imagine you have a magical dice machine. Every time you press a button, it gives you a number you can’t predict. That’s exactly what random number generation is in R!
But here’s the twist: computers aren’t actually random. They use clever math tricks to pretend to be random. And sometimes, we WANT to control this “fake randomness” so we can repeat our experiments.
🌱 Part 1: The Magic Seed (Random Seed Setting)
What is a Seed?
Think of planting a flower. If you plant the same seed in the same pot with the same water, you get the same flower every time.
R’s random number generator works the same way!
# Plant the seed
set.seed(42)
# Now pick a random number
runif(1)
# Result: 0.9148060
Run it again:
set.seed(42)
runif(1)
# Result: 0.9148060
Same seed = Same “random” number!
Why Do We Need Seeds?
| Without Seed | With Seed |
|---|---|
| Different results each time | Same results every time |
| Can’t repeat experiments | Perfect for sharing work |
| Hard to debug | Easy to find bugs |
The Magic of set.seed()
# Any number works as a seed
set.seed(123)
runif(3)
# [1] 0.288 0.788 0.409
set.seed(999)
runif(3)
# [1] 0.388 0.685 0.003
Different seeds = Different sequences!
Real-World Example: Fair Experiment
# Your friend wants to check your work
set.seed(2024)
# Generate 5 random test scores
scores <- round(runif(5, 60, 100))
print(scores)
# [1] 83 72 95 68 89
# Your friend runs the same code
# They get EXACTLY the same scores!
🎯 Part 2: Random Sampling (Picking Things Randomly)
The Lottery Ball Machine
Imagine a machine with numbered balls. You reach in and grab some without looking. That’s sample() in R!
# 10 balls numbered 1-10
# Pick 3 without looking
sample(1:10, 3)
# Result: 7 2 9 (varies each time)
Two Ways to Sample
graph TD A["🎱 Sampling"] --> B["Without Replacement"] A --> C["With Replacement"] B --> D["Each item picked once"] B --> E["Like lottery balls"] C --> F["Items can repeat"] C --> G["Like dice rolls"]
Without Replacement (Default)
Once you pick a ball, it’s gone:
# Pick 3 students from class of 5
students <- c("Amy", "Bob", "Cat", "Dan", "Eve")
sample(students, 3)
# [1] "Cat" "Amy" "Eve"
# No one is picked twice!
With Replacement
Put the ball back after each pick:
# Roll a dice 10 times
sample(1:6, 10, replace = TRUE)
# [1] 3 6 1 3 4 2 6 5 3 1
# Numbers CAN repeat (like real dice)
The Complete Recipe
sample(
x = items_to_pick_from,
size = how_many_to_pick,
replace = TRUE_or_FALSE,
prob = weights_for_each_item
)
Weighted Sampling: Unfair Dice!
What if some options should appear more often?
# Unfair coin: 70% heads, 30% tails
sample(
c("Heads", "Tails"),
size = 10,
replace = TRUE,
prob = c(0.7, 0.3)
)
# [1] "Heads" "Heads" "Tails" "Heads"...
Shuffling: Random Order
# Shuffle a deck (just first 5 cards)
cards <- c("Ace", "King", "Queen", "Jack", "10")
sample(cards)
# [1] "Queen" "10" "Ace" "Jack" "King"
# Same cards, random order!
đź”— Combining Seeds + Sampling
The real power comes when you combine them:
# Reproducible random sample!
set.seed(777)
lucky_winners <- sample(1:1000, 3)
print(lucky_winners)
# [1] 234 891 456
# Anyone with seed 777 gets
# the SAME three winners!
🎮 Quick Reference
| Function | What It Does | Example |
|---|---|---|
set.seed(n) |
Lock the randomness | set.seed(42) |
sample(x, n) |
Pick n items | sample(1:10, 3) |
replace=TRUE |
Allow repeats | sample(1:6, 10, replace=TRUE) |
prob=c(...) |
Weighted picks | prob=c(0.7, 0.3) |
🌟 Key Takeaways
- Seeds are magic keys - Same seed = Same random numbers
- Use
set.seed()before randomness - Makes experiments repeatable sample()is your lottery machine - Pick items randomlyreplace=TRUE- Put items back (can repeat)replace=FALSE- Don’t put back (no repeats)probweights - Make some options more likely
🚀 You’re Ready!
You now understand how R creates “controlled randomness.” Whether you’re:
- Running a scientific simulation
- Picking random survey respondents
- Shuffling a playlist
- Testing your code
You have the tools to make it random AND reproducible!
Remember: In R, randomness is your friend - especially when you can control it with seeds!
