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.

How to use this article

  1. 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.
  2. 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).
  3. The solutions are folded, each with the reason for every decision.
  4. Finish with the 10-question test and copy “For your script” into your .R file.

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
  1. Did each face come up 100 times? Why not, if the die is fair?
  2. What does mean(die == 5) calculate and why does it work with mean?
  3. 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?
  4. qgeom(0.9, 1/6) gives 12. How many rolls, then, guarantee you leave home 90 % of the time?
  5. 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 n Hn=n(1+12+⋯+1n) n\,H_n = n\left(1 + \tfrac12 + \dots + \tfrac1n\right) stickers; divide by 5 to turn it into packs.
  • Do the same with a for loop that stores each result in a vector, and check with identical that, with the same seed, it gives exactly the same as replicate.

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 X X 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 X X .
  • b) (4 points) With set.seed(2027), simulate 10,000 turns. Give the relative frequency table of X X to 4 decimal places and the simulated mean to 2.
  • c) (4 points) Build the theoretical distribution in R: a vector values with the possible values of X X and a vector prob with their probabilities. Check that they add up to 1 and work out E[X] E[X] to 2 decimal places.
  • d) (4 points) Calculate P(X≥10) P(X \ge 10) 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 failuresCommandWhy
Getting out on the first roll0dgeom(0, 1/6)no miss before the 5
Getting out within the first three0, 1 or 2pgeom(2, 1/6)at most three rolls is at most two misses
Rolls that are enough 90 % of the timethe 0.9 quantile, plus 1qgeom(0.9, 1/6) + 1qgeom answers in misses; the good roll goes on top
Simulating rollsfailures plus 1rgeom(5, 1/6) + 1same: 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
  1. 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.
  2. die == 5 is a logical vector with a TRUE at every 5. mean turns TRUE into 1 and FALSE into 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)
Relative frequencies of 600 rollsOutput of barplot: the six faces with relative frequencies 0.167, 0.187, 0.127, 0.170, 0.180 and 0.170, and a dashed line at 1/6.00.050.10.150.2Relative frequency0.16710.18720.12730.17040.18050.17061/6Face
Redrawn in the site colours: every bar hovers around the 1/6 line without touching it exactly.

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
  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.
  2. 12 failures, 13 rolls. qgeom(0.9, …) gives the smallest number of failures k k with P(failures≤k)≥0.9 P(\text{failures} \le k) \ge 0.9 ; in rolls, 12 + 1 = 13.
  3. Because rgeom simulates 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, 1−(5/6)3=0.4213 1 – (5/6)^3 = 0.4213 .

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: (5/6)6=0.3349 (5/6)^6 = 0.3349 .

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")
Histogram of the packs needed in 1000 albumsOutput of hist with breaks every 10 from 20 to 120: 84, 338, 309, 167, 75, 13, 9, 2, 2 and 1 albums. The median, 42, and the mean, 44.64, marked with lines.050100150200250300350Number of albums84338309167751392212030405060708090100110120— median 42— mean 44.64Packs until complete
The right tail pushes the mean above the median.

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:

  • while and not for. You do not know how many packs it will take; the while keeps going as long as a sticker is missing. A for (s in 1:100) could fall short (you have already seen a case of 113).
  • The logical vector have. Sticking in a duplicate is assigning TRUE where there was already TRUE: you do not need to ask “do I have it?” first. And all(have) is the condition for a complete album.
  • replicate versus for. They give the same (identical says TRUE) because they use up the generator’s numbers in the same order. replicate is shorter and does not need the vector allocated; the for shows every step and lets you store more than one thing per pass. With the for, allocating y <- numeric(1000) first matters: growing it with y <- 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:

PathValues of X X Probability of eachWhy
1 to 5 at the first go1 to 516 \tfrac16 not a 6: the turn ends
a 6 and then 1 to 57 to 11136 \tfrac{1}{36} two independent rolls: they multiply
6, 6 and then 1 to 513 to 171216 \tfrac{1}{216} three rolls
6, 6, 601216 \tfrac{1}{216} 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 16⋅16=136 \tfrac16 \cdot \tfrac16 = \tfrac{1}{36} ; 13 is “6, 6 and 1”, 1216 \tfrac{1}{216} ; and 0 is “6, 6, 6”, also 1216 \tfrac{1}{216} . They add up to 56+536+5216+1216=180+30+5+1216=1 \tfrac{5}{6} + \tfrac{5}{36} + \tfrac{5}{216} + \tfrac{1}{216} = \tfrac{180 + 30 + 5 + 1}{216} = 1 . The expectation is E[X]=∑x p(x)=4.10 E[X] = \sum x\,p(x) = 4.10 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
Distribution of the squares you move in a turnPaired bars, theoretical in grey and simulated in coral, for the values 0, 1 to 5, 7 to 11 and 13 to 17. From 1 to 5 they are around 0.167; from 7 to 11, 0.028; from 13 to 17 and 0, 0.005.00.030.060.090.120.150.18Probability01234578910111314151617XTheoreticalSimulatedno 6 or 12: a 6 means rolling again
Redrawn in the site colours: each pair almost matches; the simulation confirms the model.

P(X≥10)=0.0787 P(X \ge 10) = 0.0787 : 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 X X . 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 E[X] E[X] . d: 2 for the two probabilities and 2 for the paired, labelled plot.

The tail, on paper too. X≥10 X \ge 10 is 10 and 11 (136 \tfrac{1}{36} each) and 13 to 17 (1216 \tfrac{1}{216} each): 236+5216=17216=0.0787 \tfrac{2}{36} + \tfrac{5}{216} = \tfrac{17}{216} = 0.0787 , 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?

536=0.1389 \tfrac{5}{36} = 0.1389 : the first is a 6 (16 \tfrac16 ) and the second is not (56 \tfrac56 ). 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 n n (positive), it does not treat it as a vector of one element, but as “choose from 1 to n n “: 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.

Question 1Single choice

What does this code print?

set.seed(10); a <- sample(1:100, 1)
set.seed(10); b <- sample(1:100, 1)
a == b
  1. [1] TRUE
  2. [1] FALSE
  3. It depends on the run
  4. An error: sample needs replace = 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.

Question 2Single choice

What happens when you run this?

sample(c("heads", "tails"), 5)
  1. Error: you cannot draw 5 from 2 without replacement
  2. Five results of heads or tails
  3. Two results and three NAs
  4. heads tails repeated
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'”.

Question 3Short answer

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.

Question 4Single choice

What does this command return?

length(replicate(200, sum(sample(1:6, 2, replace = TRUE))))
  1. [1] 200
  2. [1] 2
  3. [1] 400
  4. [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.

Question 5Single choice

I want the probability of needing exactly 3 rolls to get the first 5 (probability 1/6 on each roll). Which command is right?

  1. dgeom(2, 1/6)
  2. dgeom(3, 1/6)
  3. pgeom(3, 1/6)
  4. 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.

Question 6Single choice

What can this code print?

left <- c(40)
sample(left, 1)
  1. Any whole number from 1 to 40
  2. Always 40
  3. An error
  4. 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)].

Question 7Single choice

What is wrong with this code?

die_mean <- function() {
  set.seed(3)
  mean(sample(1:6, 10, replace = TRUE))
}
sd(replicate(100, die_mean()))
  1. It gives 0: the 100 means are equal because the seed is inside the function
  2. It gives an error because replicate does not accept functions
  3. It gives NA because sd does not work with 100 numbers
  4. 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.

Question 8Single choice

What does this code print?

x <- c(1, 3, 3, 1)
table(factor(x, levels = 1:4))
  1. 1 2 3 4 and below 2 0 2 0
  2. 1 3 and below 2 2
  3. 1 2 3 4 and below 1 1 1 1
  4. 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.

Question 9True or false

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)
  1. all(a == b) gives TRUE.
  2. Without set.seed(1) on the second line, a and b would be equal anyway.
  3. b <- numeric(3) allocates the vector before the loop.
  4. replicate only works if the expression is a named function.
Solution
  • T — all(a == b) gives TRUE.
  • F — Without set.seed(1) on the second line, a and b would be equal anyway.
  • T — b <- numeric(3) allocates the vector before the loop.
  • F — replicate only 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.

Question 10Single choice

What does this code print?

values <- c(0, 1, 2)
prob <- c(0.5, 0.3, 0.2)
sum(values * prob)
  1. [1] 0.7
  2. [1] 1
  3. [1] 3
  4. [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, E[X]=∑x p(x)=0.7 E[X] = \sum x\,p(x) = 0.7 .

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:

  1. The simulated mean stays close to 6: with probability 1/6, it takes 6 rolls on average.
  2. Change the seed and run again: the numbers change a little, the shape does not.
  3. In the plot, the red points (dgeom) sit on the bars: the model and the simulation agree.
  4. Change 5000 to 50: 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…CodeResult
Reproducible resultsset.seed(2026)the same numbers every time
Roll a die n timessample(1:6, n, replace = TRUE)vector of faces
Draw with probabilitiessample(x, n, replace = TRUE, prob = p)according to p
One element of any vectorx[sample(length(x), 1)]always from x
Repeat an experimentreplicate(B, f())vector of B results
Relative frequency of an eventmean(x == 5) or mean(x >= 10)proportion
Table with every valuetable(factor(x, levels = v)) / Bincludes the ones that never came up
Probability of a valuedgeom(k, p), dbinom(k, n, p), dpois(k, l)number
Cumulativepgeom(k, p)P(X≤k) P(X \le k)
Quantileqgeom(0.9, p)the smallest k with P≥0.9 P \ge 0.9
Your own distributionvalues, prob; sum(prob); sum(values * prob)check 1 and E[X] E[X]

Templates from the exercises: packs_to_complete() → mean 44.64 (approximation 44.99; exact 45.39); turn() → E[X]=4.10 E[X] = 4.10 , P(X≥10)=0.0787 P(X \ge 10) = 0.0787 .

SymptomLikely cause
Every repetition gives the sameset.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 xx has a single number: use x[sample(length(x), 1)]
The theoretical and simulated bars do not pair uptable without factor(…, levels = …)
My numbers do not match the articleYou ran something else after the set.seed

Before you hand it in, ask yourself:

  1. Have I set the seed once, before simulating?
  2. Does the function simulate a single experiment, with replicate repeating it?
  3. Have I compared the simulation with the theory (or at least with a hand calculation)?
  4. Do my probabilities add up to 1?
ME1 exam coming up?The script for every topic, the printable cheat sheet and the pack for each exam, for free.See the pack

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