R intensive 2: probability and simulation — exercises with a sticker album, the dice from ludo and your own random variable (and the thousand games that were all the same)
I wanted to check in R how many times you have to roll the die in ludo (parchís, at home) to get a 5, and I simulated a thousand games with a loop: all thousand came out identical. I had put set.seed(1) inside the loop, so on every pass the generator went back to the same point and repeated the same roll, a thousand times.
This article is the hands-on part of block 2 of the R intensive. The theory, with sample, set.seed, replicate and the d/p/q/r family explained piece by piece, is in R intensive 2: probability and simulation. The probability itself (relative frequency, discrete models, expectation) is taken as known: if you need it, review it in the ME1 exercises on probability and discrete random variables. Here you program: simulate an experiment, repeat it thousands of times and compare what comes out with what the theory says.
Table of Contents
How to use this article
- Open the R playground (or RStudio). Each exercise starts with its
set.seed: with the same seed and the same order of commands, you will get exactly the same numbers as here. - Do each level before looking at the solution. Level 1: reproduce and read outputs. Level 2: write the function that simulates. Level 3: a full problem in the format of the ME1 exam script (chained parts and indicative points).
- The solutions are folded, each with the reason for every decision.
- Finish with the 10-question test and copy “For your script” into your
.Rfile.
Comparing your numbers with the article’s after running something else in between. Every sample, rgeom or replicate uses up numbers from the generator: run one extra line and everything after it changes. To compare, run again from the set.seed.
Level 1: reproduce and read the outputs
Six hundred rolls of a die and the variable “rolls until you get a 5” (the one that rules ludo when you want to leave home). Type the commands, write down what you expect and answer:
set.seed(2026) die <- sample(1:6, 600, replace = TRUE) table(die) round(table(die) / 600, 3) mean(die == 5) barplot(table(die) / 600, main = "600 rolls of the die", xlab = "Face", ylab = "Relative frequency") abline(h = 1/6, lty = 2) round(dgeom(0:3, prob = 1/6), 4) round(pgeom(2, prob = 1/6), 4) qgeom(0.9, prob = 1/6) set.seed(7) rgeom(5, prob = 1/6) + 1
- Did each face come up 100 times? Why not, if the die is fair?
- What does
mean(die == 5)calculate and why does it work withmean? dgeom(0, 1/6)is 0.1667. What does the 0 mean in R’s model? What is the probability of leaving home within the first three rolls?qgeom(0.9, 1/6)gives 12. How many rolls, then, guarantee you leave home 90 % of the time?- Why is 1 added to
rgeom?
In R, dgeom(k, p) is the probability of k failures before the first success, not of k rolls. If you are asked for “the number of rolls”, it is the number of failures plus one.
Level 2: write the function that fills the album
An album has 50 different stickers and each pack brings 5 random stickers (they can repeat, also within the same pack). Write a function packs_to_complete(n_stickers = 50, per_pack = 5) that simulates buying packs until you have them all and returns how many packs it took. Then:
- Repeat the simulation 1000 times with
replicate(seed 11) and give the mean, the median and the 90th percentile. - Compare the mean with the collector’s theoretical count: buying stickers one at a time, you need on average stickers; divide by 5 to turn it into packs.
- Do the same with a
forloop that stores each result in a vector, and check withidenticalthat, with the same seed, it gives exactly the same asreplicate.
Expected result (the first three lines):
Min. 1st Qu. Median Mean 3rd Qu. Max. 21.00 36.00 42.00 44.64 52.00 113.00
Keep which stickers you have in a logical vector have <- rep(FALSE, n_stickers). Opening a pack is have[pack] <- TRUE (duplicates do nothing) and the album is complete when all(have). As you do not know how many packs it will take, the loop is a while.
Level 3 (challenge): your turn at ludo, in the exam format
Exercise (15 points). In the ludo we play at home, on your turn you roll the die and move what comes up; if it is a 6, you move 6 and roll again; if you roll three sixes in a row, the piece goes back home and on that turn you move 0. Let be the number of squares you move in one turn.
- a) (3 points) Write a function
turn()with no arguments that simulates one turn and returns . - b) (4 points) With
set.seed(2027), simulate 10,000 turns. Give the relative frequency table of to 4 decimal places and the simulated mean to 2. - c) (4 points) Build the theoretical distribution in R: a vector
valueswith the possible values of and a vectorprobwith their probabilities. Check that they add up to 1 and work out to 2 decimal places. - d) (4 points) Calculate with the theoretical distribution and with the simulation, and draw the theoretical probabilities and the simulated frequencies side by side in one bar chart.
A turn has at most three rolls. A for loop of three passes with return() as soon as something other than a 6 comes up solves it without while; if the three passes finish, three sixes came up.
Solutions
Level 1
Before opening the solution, the plan. The first three questions look at what came up (table, mean); the last four, at what the model says (geom). And for these there is a step that comes first: translating “rolls” into “failures”, which is what R counts.
| You are asked… | In failures | Command | Why |
|---|---|---|---|
| Getting out on the first roll | 0 | dgeom(0, 1/6) | no miss before the 5 |
| Getting out within the first three | 0, 1 or 2 | pgeom(2, 1/6) | at most three rolls is at most two misses |
| Rolls that are enough 90 % of the time | the 0.9 quantile, plus 1 | qgeom(0.9, 1/6) + 1 | qgeom answers in misses; the good roll goes on top |
| Simulating rolls | failures plus 1 | rgeom(5, 1/6) + 1 | same: rgeom returns misses |
See the level 1 solution
set.seed(2026) die <- sample(1:6, 600, replace = TRUE) table(die) round(table(die) / 600, 3) mean(die == 5)
Output:
die
1 2 3 4 5 6
100 112 76 102 108 102
die
1 2 3 4 5 6
0.167 0.187 0.127 0.170 0.180 0.170
[1] 0.18
- No, and it does not have to. Each face has probability 1/6, but in 600 rolls the frequency dances around 100: here, from 76 (the 3) to 112 (the 2). The six relative frequencies go from 0.127 to 0.187, around 1/6 = 0.167. With 60,000 rolls they would stick much closer: it is the law of large numbers, which you work on in block 4.
die == 5is a logical vector with aTRUEat every 5.meanturnsTRUEinto 1 andFALSEinto 0, so the mean is the proportion of fives: 108 / 600 = 0.18. It is the shortest way to compute a relative frequency in R.
barplot(table(die) / 600, main = "600 rolls of the die", xlab = "Face", ylab = "Relative frequency") abline(h = 1/6, lty = 2)
In the plot, no bar touches the dashed 1/6 line exactly, but all of them stay close: it is what you expect from a fair die with 600 rolls.
round(dgeom(0:3, prob = 1/6), 4) round(pgeom(2, prob = 1/6), 4) qgeom(0.9, prob = 1/6) set.seed(7) rgeom(5, prob = 1/6) + 1
Output:
[1] 0.1667 0.1389 0.1157 0.0965 [1] 0.4213 [1] 12 [1] 1 3 1 2 1
- The 0 is zero failures: rolling a 5 on the first go, probability 1/6 = 0.1667. Leaving home in the first three rolls means 0, 1 or 2 failures:
pgeom(2, 1/6)= 0.1667 + 0.1389 + 0.1157 = 0.4213. Less than half the time. - 12 failures, 13 rolls.
qgeom(0.9, …)gives the smallest number of failures with ; in rolls, 12 + 1 = 13. - Because
rgeomsimulates failures. Adding 1 gives rolls: in these five games, you left home on roll 1, 3, 1, 2 and 1.
The four letters of the family are always the same: d = probability of a value, p = cumulative up to a value, q = the value that leaves a probability below it, r = simulate. What changes between models is the name (geom, binom, pois…) and the parameters.
Why mean(die == 5) and not table(die)[5] / 600. Here they give the same, but [5] is the fifth cell, not face 5, and there are only cells for the faces that came up. With the ten rolls of snippet 2 in “What’s wrong here?” (no ones and no sixes), table(d)[5] gives NA, while mean(d == 5) gives 0.2.
Writing pgeom(3, 1/6) for “the first three rolls”. It gives 0.5177, which is getting out within the first four. Check it on paper: getting out within three is not missing all three, .
Check you’ve got it: which command gives the probability of needing more than 6 rolls to get out?
pgeom(5, 1/6, lower.tail = FALSE), which is 0.3349. More than 6 rolls is 7 or more, that is, 6 failures or more; the opposite is “5 or fewer”, pgeom(5, 1/6). On paper it is missing the first six: .
Level 2
Before writing a single line, three decisions, in this order: what to remember between packs (not the stickers that came up, but which ones I have: 50 yes/no answers, a logical vector), when to stop (all(have)) and which loop (I do not know how many passes there will be: while).
And the obvious route, storing every sticker and stopping when length(unique(all_stickers)) == 50? It works, but the vector grows with every pack and you have to search for the distinct ones again; the logical one always has 50 cells.
The replace = TRUE is not a detail: the statement says a pack can bring the same sticker twice. Without it you would be simulating a different album.
See the level 2 solution
# packs_to_complete(): how many packs it takes to fill an album
packs_to_complete <- function(n_stickers = 50, per_pack = 5) {
stopifnot(n_stickers >= 1, per_pack >= 1)
have <- rep(FALSE, n_stickers) # TRUE for the stickers already stuck in
packs <- 0
while (!all(have)) { # while any is missing
pack <- sample(1:n_stickers, per_pack, replace = TRUE) # 5 stickers, they can repeat
have[pack] <- TRUE # stick them in (a duplicate changes nothing)
packs <- packs + 1
}
packs
}
set.seed(11)
x <- replicate(1000, packs_to_complete())
summary(x)
quantile(x, 0.9)
round(50 * sum(1 / (1:50)) / 5, 2) # theoretical mean in packs
Output:
Min. 1st Qu. Median Mean 3rd Qu. Max. 21.00 36.00 42.00 44.64 52.00 113.00 90% 61 [1] 44.99
How to read it: on average it takes 44.64 packs (the theory gives 44.99, less than half a pack away), but the median is 42: the distribution has a right tail. One collector in ten needs 61 packs or more, and the unluckiest of the thousand needed 113. If each pack costs 1 €, “about 45 €” is the average answer, but not the one you would give someone who does not want a nasty surprise.
hist(x, breaks = seq(20, 120, by = 10), main = "1000 simulated albums",
xlab = "Packs until complete", ylab = "Number of albums")
The tail shows in the plot: most albums are completed between 30 and 50 packs, but there are small bars up to 110. It is a right-skewed distribution, which is why the mean sits above the median.
# The same with a for loop: with the same seed, the same result
set.seed(11)
y <- numeric(1000) # allocate the vector before the loop
for (i in 1:1000) {
y[i] <- packs_to_complete()
}
identical(x, y)
Output:
[1] TRUE
Why it is written this way:
whileand notfor. You do not know how many packs it will take; thewhilekeeps going as long as a sticker is missing. Afor (s in 1:100)could fall short (you have already seen a case of 113).- The logical vector
have. Sticking in a duplicate is assigningTRUEwhere there was alreadyTRUE: you do not need to ask “do I have it?” first. Andall(have)is the condition for a complete album. replicateversusfor. They give the same (identicalsaysTRUE) because they use up the generator’s numbers in the same order.replicateis shorter and does not need the vector allocated; theforshows every step and lets you store more than one thing per pass. With thefor, allocatingy <- numeric(1000)first matters: growing it withy <- c(y, …)copies the whole vector on every pass.- Theory as a check. The simulated mean (44.64) landing half a pack from the theoretical one (44.99) is what gives you confidence in the function. If it had come out as 20 or 90, there would be a bug in the code, not in the theory.
How far can you trust 44.64? How much the mean of 1000 albums wobbles is measured like this:
# How much can the mean of 1000 simulated albums wobble? round(sd(x), 2) # how much one album varies from another round(sd(x) / sqrt(1000), 2) # how much the mean of 1000 albums varies
Output:
[1] 12.24 [1] 0.39
One album differs from another by about 12 packs; the mean of a thousand, by about four tenths. Half a pack away from the theory is normal; ten would be a bug.
Check you’ve got it: why is dividing the collector’s count by 5 only an approximation?
Because the last pack is bought whole, even if you only needed its first sticker. Counted that way, the exact mean is 45.39 packs, not 44.99; the simulation is 0.75 away, about twice the 0.39 above. For the exam the approximation is fine; what matters is knowing where the difference comes from.
Level 3
Before the code, the turn on paper. What paths can it take? Four:
| Path | Values of | Probability of each | Why |
|---|---|---|---|
| 1 to 5 at the first go | 1 to 5 | not a 6: the turn ends | |
| a 6 and then 1 to 5 | 7 to 11 | two independent rolls: they multiply | |
| 6, 6 and then 1 to 5 | 13 to 17 | three rolls | |
| 6, 6, 6 | 0 | back home |
The 6 and the 12 are missing (a 6 forces you to keep going), and so is the 18. With this table part c is already done, and part a follows the paths.
Why a three-pass for and not while (d == 6)? With the while you would have to count the sixes yourself; for (sixes in 0:2) already carries the limit in its header.
See the level 3 solution
a) The turn() function (3 points).
# ==== Exercise 3a: one turn at ludo ====
turn <- function() {
moved <- 0
for (sixes in 0:2) { # at most three rolls
d <- sample(1:6, 1)
moved <- moved + d
if (d < 6) return(moved) # no 6: the turn ends here
}
0 # three sixes in a row: back home, move 0
}
The return() inside the for is what is needed here: as soon as something other than a 6 comes up, the function ends with what it has added up. If the loop finishes its three passes without leaving, all three were 6, and the last line returns 0.
b) 10,000 turns (4 points).
# ==== Exercise 3b: simulation ==== set.seed(2027) X <- replicate(10000, turn()) round(table(X) / 10000, 4) round(mean(X), 2)
Output:
X
0 1 2 3 4 5 7 8 9 10
0.0045 0.1608 0.1629 0.1706 0.1678 0.1661 0.0288 0.0272 0.0289 0.0314
11 13 14 15 16 17
0.0280 0.0039 0.0046 0.0043 0.0053 0.0049
[1] 4.15
Values 1 to 5 each come up in around 16-17 % of turns, 7 to 11 around 3 % (a 6 and then something else), 13 to 17 around 0.5 % and 0 (three sixes) 0.45 %. The 6 never comes up, nor does the 12: a 6 forces you to keep rolling. The simulated mean is 4.15 squares per turn.
c) The theoretical distribution (4 points).
# ==== Exercise 3c: theoretical distribution ====
values <- c(0, 1:5, 7:11, 13:17)
prob <- c((1/6)^3, # 6, 6, 6: back home
rep(1/6, 5), # 1 to 5 at the first go
rep((1/6)^2, 5), # a 6 and then 1 to 5
rep((1/6)^3, 5)) # two 6s and then 1 to 5
sum(prob)
round(sum(values * prob), 2)
Output:
[1] 1 [1] 4.1
Each value is a path of rolls: 7 is “6 and then 1”, with probability ; 13 is “6, 6 and 1”, ; and 0 is “6, 6, 6”, also . They add up to . The expectation is squares; the simulation gave 4.15, a difference of 0.05 with 10,000 turns.
Writing values <- 0:17 and prob with 18 elements “to keep it simple”. The 6 and the 12 are not possible values: putting them in with probability 0 is harmless, but putting them in with 1/6 (because “there is a 6 on the die”) pushes the sum past 1. The sum(prob) line is what catches it.
d) The tail and the plot (4 points).
# ==== Exercise 3d: P(X >= 10) and comparison ====
round(sum(prob[values >= 10]), 4) # theoretical
mean(X >= 10) # simulated
simulated <- table(factor(X, levels = values)) / 10000
barplot(rbind(prob, simulated), beside = TRUE, names.arg = values,
col = c("grey80", "orange"), legend.text = c("Theoretical", "Simulated"),
main = "Squares you move in a turn", xlab = "X", ylab = "Probability")
Output:
[1] 0.0787 [1] 0.0824
: moving 10 or more in one turn happens in fewer than 8 turns out of 100; the simulation gives 0.0824. In the plot, each pair of bars almost matches: the theoretical model and the 10,000 games tell the same story. The factor(X, levels = values) is needed so the simulated table has the 16 values in the same order as prob (if a rare value had never come up, table would skip it and the bars would fall out of step).
How it is marked (indicative, my own, not official). a: 2 points for the three-sixes logic and 1 for returning . b: 2 for the simulation with a seed and 2 for the table and the mean. c: 2 for the values without the 6 and the 12, 1 for checking the sum and 1 for . d: 2 for the two probabilities and 2 for the paired, labelled plot.
The tail, on paper too. is 10 and 11 ( each) and 13 to 17 ( each): , the same as R gives.
Writing replicate(10000, turn), without brackets. It does not throw an error: it returns a list with 10,000 copies of the function; the failure shows up later, in table. You pass replicate the call, turn().
Check you’ve got it: what is the probability of rolling exactly twice in a turn?
: the first is a 6 () and the second is not (). In R, sum(prob[values %in% 7:11]), because two-roll turns are the ones ending on 7 to 11. It is the same number as dgeom(1, 1/6) in level 1: the same two factors, in a different order.
What’s wrong here?
Snippet 1. The story from the start, in miniature.
rolls <- numeric(5)
for (i in 1:5) {
set.seed(1)
rolls[i] <- sample(1:6, 1)
}
rolls
Output:
[1] 1 1 1 1 1
Five rolls, the same number. set.seed(1) resets the generator on every pass and the next sample gives the same thing again. The seed is not a “random mode”: it is the starting point of a fixed list of numbers.
Putting set.seed inside the loop or inside the function you repeat. Fix: once, before the simulation.
set.seed(1)
rolls <- numeric(5)
for (i in 1:5) {
rolls[i] <- sample(1:6, 1)
}
rolls
Output:
[1] 1 4 1 2 5
Snippet 2. Ten rolls of a die.
sample(1:6, 10)
Output:
Error in sample.int(length(x), size, replace, prob) : cannot take a sample larger than the population when 'replace = FALSE'
By default, sample draws without replacement, like someone taking balls out of a bag without putting them back: from six faces you cannot draw ten different ones. A die has its six faces again on every roll.
Ask yourself “is the object available again?”. Die, coin, roulette: replace = TRUE. Dealing cards, choosing 3 people from a list: without replacement.
set.seed(3) sample(1:6, 10, replace = TRUE)
Output:
[1] 5 2 4 4 2 3 4 2 5 2
Snippet 3. Picking at random one of my duplicate stickers to swap. Today I only have one duplicate, number 23.
dupes <- c(23) set.seed(5) sample(dupes, 1)
Output:
[1] 2
A number that is not in dupes has come out. When you give sample a single number (positive), it does not treat it as a vector of one element, but as “choose from 1 to “: sample(23, 1) is sample(1:23, 1). With two or more duplicates it worked; the bug only shows up the day you have one left, which is the worst day to find out.
Using sample(x, …) with an x whose length can be 1. Fix: pick by position, x[sample(length(x), 1)], which always returns an element of x.
set.seed(5) dupes[sample(length(dupes), 1)]
Output:
[1] 23
Test: read the code
Ten questions on reading code. They do not count and you can repeat them; try to answer without running anything.
What does this code print?
set.seed(10); a <- sample(1:100, 1) set.seed(10); b <- sample(1:100, 1) a == b
[1] TRUE[1] FALSE- It depends on the run
- An error:
sampleneedsreplace = TRUE
Solution
Answer: [1] TRUE
set.seed(10) resets the generator. Both sample calls start at the same point and give the same number, so the comparison is TRUE.
What happens when you run this?
sample(c("heads", "tails"), 5)- Error: you cannot draw 5 from 2 without replacement
- Five results of heads or tails
- Two results and three
NAs heads tailsrepeated
Solution
Answer: Error: you cannot draw 5 from 2 without replacement
Without replace = TRUE, sample draws without putting back: from two elements it can only draw two. R gives the error “cannot take a sample larger than the population when ‘replace = FALSE'”.
What number does it print? Write just the number.
x <- c(2, 5, 5, 1, 5, 6, 3, 5) mean(x == 5)
Solution
Answer: 0.5
x == 5 gives a logical vector with four TRUEs out of eight. mean counts TRUE as 1: 4 / 8 = 0.5. It is the relative frequency of the 5.
What does this command return?
length(replicate(200, sum(sample(1:6, 2, replace = TRUE))))
[1] 200[1] 2[1] 400[1] 12
Solution
Answer: [1] 200
replicate(B, expr) evaluates expr B times and binds the results. Each sum(…) is one number, so the result is a vector of 200 numbers.
I want the probability of needing exactly 3 rolls to get the first 5 (probability 1/6 on each roll). Which command is right?
dgeom(2, 1/6)dgeom(3, 1/6)pgeom(3, 1/6)dbinom(3, 3, 1/6)
Solution
Answer: dgeom(2, 1/6)
In R, the geometric counts the failures before the first success. “3 rolls” = 2 failures: dgeom(2, 1/6) = (5/6)² · (1/6) ≈ 0.1157.
What can this code print?
left <- c(40) sample(left, 1)
- Any whole number from 1 to 40
- Always
40 - An error
NA
Solution
Answer: Any whole number from 1 to 40
If the first argument is a single positive number, sample reads it as 1:n. To pick from a vector that might have one element: left[sample(length(left), 1)].
What is wrong with this code?
die_mean <- function() {
set.seed(3)
mean(sample(1:6, 10, replace = TRUE))
}
sd(replicate(100, die_mean()))- It gives
0: the 100 means are equal because the seed is inside the function - It gives an error because
replicatedoes not accept functions - It gives
NAbecausesddoes not work with 100 numbers - Nothing is wrong: it gives the standard deviation of 100 different means
Solution
Answer: It gives 0: the 100 means are equal because the seed is inside the function
The set.seed(3) inside the function makes every repetition identical: 100 equal means and a standard deviation of 0. The seed goes once, outside, before replicate.
What does this code print?
x <- c(1, 3, 3, 1) table(factor(x, levels = 1:4))
1 2 3 4and below2 0 2 01 3and below2 21 2 3 4and below1 1 1 1- An error because 2 and 4 are not in
x
Solution
Answer: 1 2 3 4 and below 2 0 2 0
factor(x, levels = …) fixes which values exist and in what order. table counts them all, including those with 0. It is what you need to pair simulated frequencies with theoretical probabilities.
About replicate and for, mark true or false.
set.seed(1); a <- replicate(3, sample(1:6, 1)) set.seed(1); b <- numeric(3) for (i in 1:3) b[i] <- sample(1:6, 1)
all(a == b)givesTRUE.- Without
set.seed(1)on the second line,aandbwould be equal anyway. b <- numeric(3)allocates the vector before the loop.replicateonly works if the expression is a named function.
Solution
- T —
all(a == b)givesTRUE. - F — Without
set.seed(1)on the second line,aandbwould be equal anyway. - T —
b <- numeric(3)allocates the vector before the loop. - F —
replicateonly works if the expression is a named function.
With the same seed and the same order of calls, replicate and the for use the same numbers from the generator. Without setting the seed again, b would start where a finished. And replicate accepts any expression. Careful: identical(a, b) would give FALSE, because a holds integers (what sample(1:6, …) returns) and b is a numeric vector: same values, different type.
What does this code print?
values <- c(0, 1, 2) prob <- c(0.5, 0.3, 0.2) sum(values * prob)
[1] 0.7[1] 1[1] 3[1] 1 0.3 0.4
Solution
Answer: [1] 0.7
values * prob multiplies element by element (0, 0.3, 0.4) and sum gives the expectation, .
Try it in the R playground
Paste this script into the R playground. It simulates the variable “rolls until you get a 5” and compares it with the geometric model.
set.seed(42)
rolls_to_5 <- function() {
n <- 1
while (sample(1:6, 1) != 5) n <- n + 1
n
}
sim <- replicate(5000, rolls_to_5())
mean(sim) # the theory says 6
mean(sim <= 3) # the theory says pgeom(2, 1/6) = 0.4213
barplot(table(factor(sim, levels = 1:20)) / 5000, main = "Rolls until a 5")
points(seq(0.7, by = 1.2, length.out = 20), dgeom(0:19, 1/6), pch = 19, col = "red")
What to look at:
- The simulated mean stays close to 6: with probability 1/6, it takes 6 rolls on average.
- Change the seed and run again: the numbers change a little, the shape does not.
- In the plot, the red points (
dgeom) sit on the bars: the model and the simulation agree. - Change
5000to50: the bars become ragged. With few repetitions, the simulation cannot be trusted.
Cheat sheet: simulation in R
The essentials in 30 seconds: set.seed once and at the start; sample(x, n, replace = TRUE) for anything that is put back; a function that simulates one experiment and replicate(B, f()) to repeat it; relative frequency with mean(condition); always compare with the theory (d/p/q).
| I want to… | Code | Result |
|---|---|---|
| Reproducible results | set.seed(2026) | the same numbers every time |
| Roll a die n times | sample(1:6, n, replace = TRUE) | vector of faces |
| Draw with probabilities | sample(x, n, replace = TRUE, prob = p) | according to p |
| One element of any vector | x[sample(length(x), 1)] | always from x |
| Repeat an experiment | replicate(B, f()) | vector of B results |
| Relative frequency of an event | mean(x == 5) or mean(x >= 10) | proportion |
| Table with every value | table(factor(x, levels = v)) / B | includes the ones that never came up |
| Probability of a value | dgeom(k, p), dbinom(k, n, p), dpois(k, l) | number |
| Cumulative | pgeom(k, p) | |
| Quantile | qgeom(0.9, p) | the smallest k with |
| Your own distribution | values, prob; sum(prob); sum(values * prob) | check 1 and |
Templates from the exercises: packs_to_complete() → mean 44.64 (approximation 44.99; exact 45.39); turn() → , .
| Symptom | Likely cause |
|---|---|
| Every repetition gives the same | set.seed inside the loop or the function |
| “cannot take a sample larger than the population” | replace = TRUE is missing |
sample(x, 1) gives a value not in x | x has a single number: use x[sample(length(x), 1)] |
| The theoretical and simulated bars do not pair up | table without factor(…, levels = …) |
| My numbers do not match the article | You ran something else after the set.seed |
Before you hand it in, ask yourself:
- Have I set the seed once, before simulating?
- Does the function simulate a single experiment, with
replicaterepeating it? - Have I compared the simulation with the theory (or at least with a hand calculation)?
- Do my probabilities add up to 1?
For your script
The block’s code, commented and without problem statements, for your .R file.
# ===================== Block R2: probability and simulation =====================
# freq_vs_theory(x, values, prob): simulated frequencies against theoretical ones, in a table
freq_vs_theory <- function(x, values, prob, digits = 4) {
stopifnot(length(values) == length(prob), abs(sum(prob) - 1) < 1e-8)
sim <- as.vector(table(factor(x, levels = values))) / length(x)
data.frame(value = values, theory = round(prob, digits), simulated = round(sim, digits))
}
# expectation(values, prob) and variance(values, prob) of a discrete variable
expectation <- function(values, prob) sum(values * prob)
variance <- function(values, prob) sum((values - expectation(values, prob))^2 * prob)
# pick(x, n): n elements of x at random, even if x has a single element
pick <- function(x, n = 1, ...) x[sample(length(x), n, ...)]
# simulate(f, B, seed): repeat an experiment f() B times with a seed
simulate <- function(f, B = 10000, seed = NULL) {
if (!is.null(seed)) set.seed(seed)
replicate(B, f())
}
# The d/p/q/r family (swap geom for binom, pois, nbinom, hyper…):
# dgeom(k, p) P(X = k) (k failures before the first success)
# pgeom(k, p) P(X <= k) qgeom(a, p) smallest k with P(X <= k) >= a rgeom(n, p) simulates n
# Quick check with ludo freq_vs_theory(X, values, prob)[1:4, ] round(c(E = expectation(values, prob), Var = variance(values, prob)), 2)
Output:
value theory simulated 1 0 0.0046 0.0045 2 1 0.1667 0.1608 3 2 0.1667 0.1629 4 3 0.1667 0.1706 E Var 4.10 9.16
simulate(turn, 10000, 2027) reproduces part b of level 3 in one go. Passing the function without brackets (turn, not turn()) is what lets simulate call it whenever it wants.
What next?
If replicate, set.seed or the d/p/q/r family still wobble, go back to the block’s theory, R intensive 2: probability and simulation. And for the pen-and-paper side, the ME1 discrete random variables exercises work on the same distributions with the exam’s marking.
The next block is R intensive 3: normal and joint distributions: vectorising with ifelse and sapply, the normal inside your functions and how long a loop takes compared with a vector.
Did this article help you? Here is how you can support SergioLearns →
Next blockR intensive 3: normal and joint distributions — Working with the whole vector: ifelse, sapply and apply, the normal inside your functions and how long a loop takesBlock theory: sample, set.seed, replicate and the d/p/q/r familyR intensive 2: probability and simulationCheat sheet: the block on one page, to reviewCheat sheetScript: the block's functions, ready for your .RFor your script


