R intensive 2: probability and simulation — sample, set.seed and replicate with the sticker packets of an album (and the seed I forgot to set)

Simulating is asking R to repeat an experiment thousands of times and counting what happens. The first time I did it for a probability lab I spent half an hour convinced my code was broken: every time I ran it I got a different result, and my classmate’s looked like none of mine. There was no bug. One single line was missing, set.seed(), and without it R’s randomness is real randomness: it changes every run.

In this second block of the intensive, probability is taken as known (you have it in ME1 topics 2, 3 and 4). Here we learn to program random experiments: draw samples with sample, make randomness repeatable, repeat an experiment with replicate or with a for loop, use the d/p/q/r family inside your code and check a theoretical probability by simulating.

In a nutshell: to simulate in R you combine sample() (draw at random, with or without replacement and with probabilities), set.seed() (make the randomness repeatable), replicate() or a for loop (repeat the experiment) and the d/p/q/r functions of each distribution. The relative frequency of what you simulate gets close to the theoretical probability, and that lets you check any calculation done by hand.

Before you start. To follow this block you only need two things. From R: vectors, %in%, your own functions and for and while loops (if any of them feels shaky, go over it in R from scratch and in block 1 of the intensive course). From probability: knowing what a relative frequency is and recognising a binomial and a hypergeometric (topics 2 and 3); you do not need to remember their formulas, R computes them for you. The article has three parts, in this order. First, the separate pieces: drawing at random with sample, repeating randomness with set.seed and repeating an experiment with replicate. Then, the idea that justifies everything: if you repeat an experiment many times, the proportion of times something happens gets close to its probability, and that is why a simulation can check a calculation done by hand (we do it with the binomial, with a made-up variable and with the hypergeometric). Finally, a complete program written three times, each one better: how many packets it takes to complete the album. If you get lost at any point, go back to the packet of 5 stickers: the whole article is opening packets and counting.

What you are going to program (and for which topic)

The example in this block: a sticker album of 50 stickers sold in packets of 5, all different within each packet. Sticker number 1 is the gold one. The questions we have all asked ourselves at some point: how many packets does it take to complete it? How often will I get the gold one? When I already have 30, how many repeats does a new packet bring?

Some have a theoretical answer you know how to work out with topics 2 and 3 (the gold one is a binomial; the repeats, a hypergeometric). Others, like completing the album, get very complicated by hand. Simulation is good for both: checking the easy calculations and answering the hard ones.

What you are going to build:

  • A random packet with sample and an experiment repeated thousands of times with replicate.
  • The check that the relative frequency converges to the probability.
  • A discrete variable of your own, simulated and compared with the theoretical one (with dhyper).
  • A packets_to_complete() function and its distribution with 2000 simulated albums, with for and with replicate.

If you want to see how these functions are used to solve the problems of the topic, that is in the R practice of topics 2 and 3. Here we focus on how the code is written.

The R pieces you need

sample: drawing at random

sample(x, size) draws size elements of x at random, without replacement by default: exactly what a packet is, five different stickers.

# A packet: 5 different stickers out of an album of 50
sample(1:50, 5)
sample(1:50, 5)

Output:

[1] 12 40 30 22  3
[1] 31 26 20 12 48

Two packets, two different results. Normal: it is random. And if you run it, you will get different ones. That, which is exactly what we want from a packet, is a problem for a report or an exam: nobody can check your numbers.

set.seed: making randomness repeatable

A computer’s randomness is not random: it is a sequence of numbers that looks random and comes from a starting point, the seed. If you fix the seed, the sequence is always the same:

# With set.seed randomness can be repeated: same seed, same packet
set.seed(2026)
sample(1:50, 5)
set.seed(2026)
sample(1:50, 5)

Output:

[1] 29 33 38 45 27
[1] 29 33 38 45 27

The same packet both times: 29, 33, 38, 45 and 27. On your computer, with set.seed(2026), you will get that one too (with the same version of R; from R 3.6 on all versions give the same).

Setting set.seed() once at the top of the script and then running only a piece from the middle. The seed fixes the sequence from that point: if you skip lines that drew random numbers, the next ones change. Put the seed right before each simulation you want to be able to repeat.

The seed, line by line

The box above is easier to understand when you watch it happen. We set the seed once and draw two packets in a row; then we set it again and draw one more:

# One seed, two packets in a row, and the same seed again
set.seed(2026)
sample(1:50, 5)   # first packet after the seed
sample(1:50, 5)   # second packet: the sequence carries on, it does not start over
set.seed(2026)
sample(1:50, 5)   # seed again: the first packet comes back

Output:

[1] 29 33 38 45 27
[1] 44 36 48  5 31
[1] 29 33 38 45 27
LineResultWhy
set.seed(2026)nothingit puts the sequence of “random” numbers at its starting point
first sample29 33 38 45 27it uses up the first numbers of the sequence
second sample44 36 48 5 31the seed is not reset on its own: it carries on from where it was and uses up the next ones
set.seed(2026)nothingit takes the sequence back to the same starting point
third sample29 33 38 45 27the same numbers as the first one, because it starts from the same place

So the seed does not “freeze” a result: it fixes where the sequence starts. The second packet is reproducible too, but only if the first one has been run before it. If you delete the first sample from the script, the one that was second now gives 29 33 38 45 27. That is exactly what the box says: skipping lines that drew random numbers changes everything that comes after.

replace and prob: dice and weighted draws

With replace = TRUE each draw “goes back into the bag”, so it can repeat: it is a die. And with prob each value has its own probability:

# replace = TRUE: each draw goes back into the bag (a die rolled 10 times)
set.seed(1)
sample(1:6, 10, replace = TRUE)
# prob: values with different probabilities
set.seed(1)
sample(c("normal", "shiny"), 10, replace = TRUE, prob = c(0.8, 0.2))

Output:

 [1] 1 4 1 2 5 3 6 2 3 3
 [1] "normal" "normal" "normal" "shiny"  "normal" "shiny"  "shiny" 
 [8] "normal" "normal" "normal"

The die gives three threes and two ones. In the second draw, 3 out of 10 stickers are shiny, even though the probability is 0.2: with 10 draws, 3 is perfectly possible. For the proportion to look like 0.2 you need many more, and that is what comes next.

replicate: repeating an experiment

replicate(n, expression) evaluates the expression n times and puts the results together in a vector:

# replicate(n, expression): repeats the expression n times and combines the results
set.seed(7)
replicate(6, 1 %in% sample(1:50, 5))   # does the packet have the gold sticker (number 1)?

Output:

[1] FALSE FALSE FALSE FALSE FALSE FALSE

Six packets and none had the gold one. Bad luck? Not so much: the probability that a packet does not have it is 45/50 = 0.9, so six in a row without it is 0.9⁶ ≈ 0.53. It happens more than half the time.

The expression 1 %in% sample(1:50, 5) deserves a zoom: sample draws the packet and %in% asks whether 1 is in it. It returns TRUE or FALSE, and since in R TRUE is 1 and FALSE is 0, the mean of many TRUE/FALSE values is the proportion of times it happened. You will use that trick in almost every simulation.

Where the 0.9 and the 0.53 come from

That calculation goes fast, so let’s take it in parts. A packet is 5 different stickers chosen out of 50, and every sticker has the same chance of being in it. If there are 5 slots for 50 stickers, each sticker, the gold one included, is in the packet with probability 5/50 = 0.1.

StepCalculationWhy
1P(the packet has the gold one) = 5/50 = 0.15 of the 50 stickers go into the packet and none is preferred
2P(it does not) = 1 − 0.1 = 0.9 = 45/50it is the complement of step 1
3P(six packets without it) = 0.9 · 0.9 · 0.9 · 0.9 · 0.9 · 0.9 = 0.9⁶each packet is independent of the others, so the probabilities multiply
40.9⁶ = 0.531441 ≈ 0.53R confirms it with 0.9^6

And the TRUE/FALSE trick, with a small vector so you can see it by hand: mean(c(TRUE, FALSE, FALSE, TRUE)) adds 1 + 0 + 0 + 1 = 2 and divides it by 4 values, 0.5. It happened half the time, and the mean says so. sum of the same vector gives 2: how many times it happened. With mean you get a proportion; with sum, a count.

Check you’ve got it: what number do you expect mean(replicate(1000, 1 %in% sample(1:50, 5))) to give? And if you change mean to sum?

With mean, a number close to 0.1. replicate opens 1000 packets and writes TRUE for the ones that have the gold sticker; the mean of those TRUE/FALSE values is the proportion of packets with the gold one, and the probability for each packet is 5/50 = 0.1. It will not be exactly 0.1: it is chance, and with 1000 packets it is normal to be a few hundredths off.

With sum, a number close to 100: it counts how many of the 1000 packets had the gold sticker, and 10 % of 1000 is 100. It is the same information, counted another way: sum divided by 1000 is mean.

The relative frequency gets close to the probability

If we open the packet many times and keep computing the proportion of gold stickers, it should get close to 5/50 = 0.1 (the gold one is in the packet if it is one of the 5 chosen out of 50).

# The relative frequency gets close to the probability (5/50 = 0.1)
set.seed(11)
gold <- replicate(5000, 1 %in% sample(1:50, 5))
freq <- cumsum(gold) / seq_along(gold)   # relative frequency after each packet
round(freq[c(10, 100, 1000, 5000)], 3)

Output:

[1] 0.000 0.070 0.119 0.100

cumsum(gold) keeps adding up the TRUEs (how many gold stickers I have after each packet) and seq_along(gold) is 1, 2, 3… (how many packets I have opened). Their ratio is the relative frequency at each moment. After 10 packets, 0 gold ones; after 100, 7 %; after 1000, 11.9 %; and after 5000, exactly 0.100. Drawn, it is easier to see:

plot(freq, type = "l", log = "x", ylim = c(0, 0.3),
     main = "How many packets have the gold one?", xlab = "Packets opened",
     ylab = "Relative frequency")
abline(h = 0.1, lty = 2, col = "#FF6B4A")
The relative frequency of the gold stickerLine of the relative frequency of packets with the gold sticker after each packet, from 1 to 5000 on a log scale. It starts at 0, jumps a lot and from about a thousand packets on it stays close to the dashed line at 0.1.00.10.20.3Packets opened (log scale)Relative frequencyHow many packets have the gold one?1101001,0005,000probability 0.1
With few packets the proportion jumps; with thousands, it settles at the probability, 0.1.

In the drawing, at first the line jumps a lot (each gold sticker moves the proportion a lot when you have opened few packets) and from about a thousand on it sticks to the dashed line at 0.1. It is the law of large numbers you will see in topic 7, but here the idea is about programming: log = "x" puts the horizontal axis on a log scale so you can see the first 10 packets and the 5000 at the same time.

The relative frequency, packet by packet

The freq line does a lot in very little space. With 5000 packets you cannot follow it by hand, so we try it with five made-up packets, in which the gold one comes out in the second and the fifth:

# Five made-up packets, to follow the calculation by hand
gold <- c(FALSE, TRUE, FALSE, FALSE, TRUE)
cumsum(gold)                              # gold stickers so far
seq_along(gold)                           # packets opened
round(cumsum(gold) / seq_along(gold), 2)  # relative frequency

Output:

[1] 0 1 1 1 2
[1] 1 2 3 4 5
[1] 0.00 0.50 0.33 0.25 0.40
Packetgoldcumsumseq_alongFrequencyWhy
1FALSE010/1 = 0no gold sticker yet
2TRUE121/2 = 0.5the TRUE adds 1; one gold sticker in two packets
3FALSE131/3 = 0.33the FALSE adds 0: the count stays, the packets go up
4FALSE141/4 = 0.25it drops again, because the denominator grows and the numerator does not
5TRUE252/5 = 0.4the second gold sticker pushes it back up

With five packets, the frequency jumps by 0.25 or more each time: each packet weighs a fifth. With 5000, a packet weighs 1/5000 and the line hardly moves. That is what you see in the drawing. In the real simulation (with set.seed(11)) the first gold sticker does not arrive until packet 26, and that is why after 10 packets the frequency was 0: it is not that the probability is 0, it is that ten packets are very few.

The d/p/q/r family inside your code

Every distribution in R has four functions with the same name and a letter in front. The number of gold stickers in 20 packets is a binomial with size = 20 and prob = 0.1:

# The d/p/q/r family: gold stickers in 20 packets ~ Binomial(20, 0.1)
dbinom(2, size = 20, prob = 0.1)     # P(X = 2)
pbinom(2, size = 20, prob = 0.1)     # P(X <= 2)
qbinom(0.9, size = 20, prob = 0.1)   # the smallest x with P(X <= x) >= 0.9
set.seed(3)
rbinom(8, size = 20, prob = 0.1)     # 8 simulations of X

Output:

[1] 0.2851798
[1] 0.6769268
[1] 4
[1] 1 3 1 1 2 2 1 1
The four letters on the Binomial(20, 0.1)Bars of the mass function of a binomial with 20 trials and probability 0.1, from 0 to 8. The bar at 2 is highlighted (d = 0.285); a bracket spans 0 to 2 (p = 0.677); a vertical line marks 4 (q(0.9) = 4); and a box shows 8 values simulated with rbinom.00.10.20.3Gold stickers in 20 packetsProbability012345678d: 0.285p: sum up to 2 = 0.677q(0.9) = 4first x with p ≥ 0.9r: random values1 3 1 1 2 2 1 1rbinom(8, 20, 0.1)
d is one bar, p the sum up to a value, q the reverse of p and r simulated values.

The drawing shows what each letter returns on the bars of the binomial: d is the height of one bar (P(X = 2) = 0.285), p is the sum of the bars up to a value (P(X ≤ 2) = 0.677), q does the opposite of p (you give it 0.9 and it tells you that up to 4 gold stickers you build up at least 90 %) and r draws random values (8 rounds of 20 packets, with 1, 3, 1, 1, 2, 2, 1 and 1 gold stickers).

LetterYou give itIt returnsExample
da valueits probability (or density)dbinom(2, 20, 0.1) = 0.285
pa valuethe cumulative probability up to itpbinom(2, 20, 0.1) = 0.677
qa probabilitythe value that builds it upqbinom(0.9, 20, 0.1) = 4
rhow many you wantsimulated valuesrbinom(8, 20, 0.1)

It works the same with all of them: dpois, pexp, qnorm, runif, dhyper… The word changes, not the logic.

qbinom, row by row

Of the four letters, q is the hardest, because it goes “backwards”. The easiest way is to get the bars and their sums from 0 to 5 gold stickers and look them up in a table:

# The bars and their sums, from 0 to 5 gold stickers in 20 packets
round(dbinom(0:5, size = 20, prob = 0.1), 3)   # P(X = x)
round(pbinom(0:5, size = 20, prob = 0.1), 3)   # P(X <= x)

Output:

[1] 0.122 0.270 0.285 0.190 0.090 0.032
[1] 0.122 0.392 0.677 0.867 0.957 0.989
xP(X = x)P(X ≤ x)Does it reach 0.9?Why
00.1220.122Nothe first sum is the bar itself
10.2700.392No0.122 + 0.270
20.2850.677No0.392 + 0.285: it is the pbinom(2, …) from the code above
30.1900.867No0.677 + 0.190: still short
40.0900.957Yes0.867 + 0.090: the first sum that goes past 0.9

qbinom(0.9, …) goes down the third column and stops at the first row that reaches 0.9: x = 4. In a discrete variable there is almost never a value that builds up exactly 0.9, which is why the definition says “the smallest x with P(X ≤ x) ≥ 0.9”.

And the 0.285 from dbinom is not magic: it is the binomial formula you already know. 2 gold stickers in 20 packets: C(20, 2) = 190 ways of choosing which two packets, times 0.1² for those two to have it, times 0.9¹⁸ for the other 18 not to. 190 · 0.01 · 0.150 = 0.285.

Check you’ve got it: what does qbinom(0.5, size = 20, prob = 0.1) return?

It returns 2. With the table: P(X ≤ 0) = 0.122 does not reach 0.5; P(X ≤ 1) = 0.392 does not either; P(X ≤ 2) = 0.677 does. The first row that reaches it is the one for 2. Since 0.5 is half, what you have just computed is the median of the gold stickers in 20 packets: in half of the rounds of 20 packets you will get 2 gold stickers or fewer.

A discrete variable of your own

And if your variable is not a binomial, nor a Poisson, nor anything with a name? With sample and prob you can simulate any of them. Imagine the number of shiny stickers in a packet is 0, 1 or 2 with probabilities 0.70, 0.25 and 0.05:

# A discrete variable of your own: shiny stickers in a packet
values <- 0:2
p <- c(0.70, 0.25, 0.05)
sum(values * p)                        # theoretical E[X]
set.seed(5)
x <- sample(values, 10000, replace = TRUE, prob = p)
mean(x)                                # simulated mean
round(table(x) / length(x), 3)         # relative frequencies

Output:

[1] 0.35
[1] 0.3573
x
    0     1     2 
0.696 0.251 0.053 

The theoretical expectation is 0 · 0.70 + 1 · 0.25 + 2 · 0.05 = 0.35, and the mean of 10,000 simulated packets, 0.3573. The relative frequencies (0.696, 0.251 and 0.053) look like the probabilities (0.70, 0.25 and 0.05) to two decimals. With that you have checked the whole variable: its mass function and its mean.

sum(values * p) is the definition of expectation written in R: it multiplies vector by vector, element by element, and adds up. The variance comes out the same way: sum((values - 0.35)^2 * p).

The variance, cell by cell

The line sum((values - 0.35)^2 * p) is the definition of variance: the mean, weighted by the probabilities, of how far each value falls from the expectation, squared. Written as a table, each cell is a step of the vector:

xpx − 0.35(x − 0.35)²(x − 0.35)² · pWhy
00.70−0.350.12250.0858values - 0.35 subtracts the expectation from each value
10.250.650.42250.1056^2 squares each distance, so the negative ones do not cancel out the positive ones
20.051.652.72250.1361* p weights: 2 is far away, but it rarely comes up

The sum of the last column is 0.0858 + 0.1056 + 0.1361 = 0.3275, about 0.33. Checked with R, next to the variance of the 10,000 simulated packets (with the values, p and x from above):

# The theoretical variance and that of the 10,000 simulated packets
sum((values - 0.35)^2 * p)   # theoretical Var(X)
round(var(x), 2)             # simulated variance

Output:

[1] 0.3275
[1] 0.34

The simulated one (0.34) is one hundredth away from the theoretical one (0.33), just as happened with the mean. If you prefer the other formula from topic 3, E[X²] − E[X]², you get the same: sum(values^2 * p) is 0 · 0.70 + 1 · 0.25 + 4 · 0.05 = 0.45, and 0.45 − 0.35² = 0.45 − 0.1225 = 0.3275.

Check you’ve got it: why does sample(values, 10000, replace = TRUE, prob = p) need replace = TRUE?

Because each packet is a new experiment: one packet having 1 shiny sticker does not stop the next one from having 1 too. The values have to be able to repeat, just like the faces of a die.

Without replace = TRUE, sample draws without replacement, and from a vector of 3 values (0, 1 and 2) you can only draw 3 different ones. Asking it for 10,000 gives the error from the common mistakes section: “cannot take a sample larger than the population when ‘replace = FALSE'”.

Simulated against theoretical: the repeats in a packet

A real case: I have 30 stickers out of the 50 (numbers 1 to 30, to keep it simple). How many of the 5 in a new packet will be repeats? If you think about it, it is drawing 5 without replacement from a bag with 30 “repeats” and 20 “new ones”: a hypergeometric, which R has as dhyper.

# Stickers I already have in a new packet when I have 30 of 50: simulated against theoretical
set.seed(8)
have <- 1:30
repeats <- replicate(10000, sum(sample(1:50, 5) %in% have))
simulated <- table(factor(repeats, levels = 0:5)) / 10000
theoretical <- dhyper(0:5, m = 30, n = 20, k = 5)
round(rbind(simulated, theoretical), 3)

Output:

                0     1     2     3     4     5
simulated   0.006 0.067 0.234 0.366 0.259 0.068
theoretical 0.007 0.069 0.234 0.364 0.259 0.067

The two rows match almost to the thousandth: the most likely outcome is that it brings 3 repeats (0.366 simulated, 0.364 theoretical) and the least likely, that it brings none (0.006 and 0.007). That is how you check that you chose the right model.

Three details in the code:

  • sum(… %in% have) counts how many stickers in the packet are in have: that is the variable we simulate.
  • factor(repeats, levels = 0:5) forces table to count the values that never came up as well. Without it, if no 0 had come up in 10,000 packets, the table would have 5 columns instead of 6, and rbind would mix the columns with the theoretical ones.
  • rbind puts the two rows one above the other to compare them.

The chart that compares them at a glance:

barplot(rbind(simulated, theoretical), beside = TRUE, names.arg = 0:5,
        col = c("#A99EF5", "#FF6B4A"), legend.text = c("simulated", "theoretical"),
        main = "Repeats in a packet (I have 30 of 50)",
        xlab = "Repeated stickers", ylab = "Probability")
Repeats in a packet: simulated against theoreticalGrouped bars from 0 to 5 repeats. Simulated: 0.006, 0.067, 0.234, 0.366, 0.259 and 0.068. Theoretical (hypergeometric): 0.007, 0.069, 0.234, 0.364, 0.259 and 0.067.00.10.20.30.4Repeated stickersProbabilityRepeats in a packet (I have 30 of 50)012345simulatedtheoretical
Each pair of bars is almost the same height: the hypergeometric was the right model.

In the drawing, each pair of bars is almost the same height: the violet one (simulated) and the coral one (theoretical) only differ in the third decimal. If a pair did not match, the theoretical model would be the wrong choice (or the simulation, badly written). beside = TRUE is what puts the bars side by side instead of stacked.

dhyper, argument by argument

dhyper(0:5, m = 30, n = 20, k = 5) reads better if you translate each argument into the album. R’s hypergeometric talks about an urn with white and black balls, and all you have to do is decide what “white” is:

ArgumentValueWhat it is in the albumWhy
x0:5how many repeats the packet bringsit is what we count: the “successes” that come out
m30stickers I already havethey are the “white balls”: the ones that, if they come out, are repeats
n20stickers I am missingthe “black” ones: the rest of the urn, not the total
k5stickers in a packethow many balls are drawn, without replacement

With that, the probability of 3 repeats can be done by hand: choosing 3 of the 30 I have, C(30, 3) = 4060 ways; and 2 of the 20 I am missing, C(20, 2) = 190; out of all possible packets, C(50, 5) = 2,118,760. That leaves 4060 · 190 / 2,118,760 = 771,400 / 2,118,760 = 0.364: the same 0.364 as in the theoretical row.

Writing n = 50 thinking that n is the total number of stickers. In dhyper, n is the number of balls of the other colour, not the size of the urn. With dhyper(3, m = 30, n = 50, k = 5) R gives no error at all: it computes a different urn, with 80 stickers, and returns 0.21 instead of 0.36. The simulation would give it away at once, because its row would not look like the theoretical one.

The complete program: how many packets to complete the album?

This question has no binomial behind it. It can be solved by hand with a lot of patience, but with R it is enough to do what a person would do: open packets until you have all 50, count how many it took, and repeat that thousands of times.

Version 1: one album, by hand

# Version 1: one album, by hand, with while
set.seed(42)
album <- rep(FALSE, 50)      # FALSE = I am missing that sticker
packets <- 0
while (!all(album)) {
  album[sample(1:50, 5)] <- TRUE
  packets <- packets + 1
}
packets

Output:

[1] 38

The album is a vector of 50 FALSE values (“missing”). In each lap a packet comes out and its 5 positions become TRUE; if I already had it, nothing changes (a repeat). all(album) is TRUE only when all 50 are there, so while (!all(album)) keeps going while any is missing. With this seed it took 38 packets. This is how the album evolves in the first laps:

LapWhat happensStickers I haveall(album)
0empty album0FALSE
15 stickers, all new5FALSE
25 stickers, some may be repeatsbetween 5 and 10FALSE
…more and more repeatsgrows more and more slowlyFALSE
38the last missing one comes out50TRUE: it stops

The table above is the general idea. With seed 42 you can see the real trace: all it takes is writing down, in each lap, how many TRUE values the album has.

# Version 1, writing down how many stickers I have after each packet
set.seed(42)
album <- rep(FALSE, 50)
packets <- 0
owned <- numeric(0)              # the trace is written down here
while (!all(album)) {
  album[sample(1:50, 5)] <- TRUE
  packets <- packets + 1
  owned[packets] <- sum(album)   # how many TRUE values there are now
}
owned
diff(c(0, owned))                # new stickers in each packet

Output:

 [1]  5 10 12 15 18 22 25 29 30 31 33 37 38 40 41 42 42 42 43 45 48 48 49 49 49
[26] 49 49 49 49 49 49 49 49 49 49 49 49 50
 [1] 5 5 2 3 3 4 3 4 1 1 2 4 1 2 1 1 0 0 1 2 3 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1

Since drawing packets uses up the same sequence as version 1, it also ends at packet 38. The second line is the difference between one lap and the one before, that is, how many new stickers each packet brought:

PacketsStickers I haveNew per packetWhy
1 and 25 and 105 and 5with the album almost empty, everything is usually new
3122I already have 10 of 50: three of the five were repeats
9 to 16from 30 to 42between 1 and 4with more than half, each packet brings mostly repeats
17 and 18420whole packets of repeats: the album does not move
23491only one sticker is missing
24 to 37490fourteen packets in a row without the missing one
38501at last: all(album) is TRUE and the while stops

Half the album (25 stickers) fills up in 7 packets; the last sticker, on its own, takes 15 (from 24 to 38). You will see it in general at the end of the article.

Check you’ve got it: if a packet brings a sticker I already had, why does album[sample(1:50, 5)] <- TRUE not count it twice?

Because the album does not count: it records. Each position of album is TRUE or FALSE, “I have it” or “I am missing it”. If sticker 12 was already TRUE and comes out again, the line writes TRUE where there was already TRUE, and nothing changes.

That is why sum(album) counts different stickers and not stickers opened. In packet 3, for example, 15 stickers had been opened in total, but sum(album) gives 12: the 3 repeats were written on top of a TRUE that was already there. If you wanted to count repeats you would have to store numbers instead of TRUE/FALSE (with album[s] <- album[s] + 1, for example).

But one album is an anecdote. To know how many packets it takes in general, you have to repeat it, and to repeat it without copying the while, you need a function.

Version 2: a function

# Version 2: the same simulation inside a function
packets_to_complete <- function(n_stickers = 50, per_packet = 5) {
  stopifnot(per_packet <= n_stickers)
  album <- rep(FALSE, n_stickers)
  packets <- 0
  while (!all(album)) {
    album[sample(n_stickers, per_packet)] <- TRUE
    packets <- packets + 1
  }
  packets
}
set.seed(42)
packets_to_complete()
packets_to_complete(n_stickers = 10, per_packet = 5)

Output:

[1] 38
[1] 5

With the same seed, the function gives the same 38 packets as version 1: it is the same code, only stored. And since the size of the album and of the packet are arguments, it works for any collection: an album of 10 with packets of 5 was completed in 5 packets.

Two details: sample(n_stickers, per_packet) with a single number is the same as sample(1:n_stickers, per_packet); and stopifnot(per_packet <= n_stickers) avoids an odd error from sample deeper down (packets bigger than the album).

Writing a simulation with a while without thinking whether it always ends. Here it ends with probability 1, but if per_packet were 0 it would never stop. Before launching 2000 repetitions, try the function on a small case.

Version 3: repeat it 2000 times, with for and with replicate

There are two ways to repeat a simulation in R. With a for loop, creating the vector to store the results beforehand; or with replicate, which does that same thing inside:

# Version 3a: repeat it 2000 times with a for loop (vector created beforehand)
set.seed(100)
res_for <- numeric(2000)
for (i in 1:2000) {
  res_for[i] <- packets_to_complete()
}
# Version 3b: the same with replicate
set.seed(100)
res <- replicate(2000, packets_to_complete())
identical(res_for, res)

Output:

[1] TRUE

identical says TRUE: with the same seed, both give exactly the same 2000 numbers. There is no magic in replicate: it is a loop someone else wrote.

for versus replicateOn the left, the for loop that creates a 2000-element vector and fills it; on the right, the same simulation with replicate. Below, their pros and cons and the check identical(res_for, res), which gives TRUE.Two ways to repeat, the same resultforreplicateset.seed(100)res <- numeric(2000)for (i in 1:2000) { res[i] <- packets_to_complete()}set.seed(100)res <- replicate(2000, packets_to_complete())+ you can use i and store several things+ you can stop early (break)− you must create the vector first+ shorter, no index+ you cannot forget the vector− one thing per repetitionidentical(res_for, res) → TRUE
replicate is a loop someone else wrote: with the same seed it gives the same 2000 numbers.

Which one should I use? The drawing sums it up. replicate is shorter and does not let you forget the results vector; the for loop is more flexible (you can use i, store two things per lap or stop early). In both cases, what matters is what goes inside: a function that does one experiment and returns a number.

If in the for loop you create an empty vector (res <- c()) and grow it with res <- c(res, new), it works, but R copies the whole vector in every lap. With 2000 laps you will not notice; with a million, you will. numeric(2000) reserves the space in one go. In block 3 we will measure it with system.time.

And now, what we wanted to know:

summary(res)
round(sd(res), 2)
mean(res <= 45)                       # P(complete it with 45 packets or fewer)
quantile(res, 0.9)                    # how many packets complete it 90 % of the time

Output:

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  21.00   35.00   42.00   43.74   50.00  115.00 
[1] 12.07
[1] 0.6405
90% 
 60 

How to read each number:

  • Mean 43.74 packets (218.7 stickers for an album of 50: about 169 repeats on average).
  • Median 42: half the albums are completed with 42 packets or fewer.
  • Minimum 21 and maximum 115: someone very lucky and someone very unlucky. With 50 stickers and packets of 5 you need at least 10, but nobody manages it in practice.
  • mean(res <= 45) = 0.6405: with 45 packets you complete the album 64 % of the time. It is the TRUE/FALSE trick: the mean of the condition is its estimated probability.
  • 90 % quantile = 60: if you want to be “almost sure” (9 times out of 10), buy 60 packets.
hist(res, breaks = seq(20, 120, by = 5), main = "Packets to complete the album",
     xlab = "Packets", ylab = "Number of simulations", col = "#A99EF5", border = "white")
abline(v = mean(res), col = "#FF6B4A", lwd = 2)
Histogram of the packets needed in 2000 albumsHistogram with 5-packet classes from 20 to 120. The tallest classes are between 30 and 45 packets (305, 397 and 376 simulations); the right tail reaches 115. A vertical coral line marks the mean, 43.74.0100200300400PacketsNumber of simulationsPackets to complete the album2030405060708090100110120mean 43.74
Skewed to the right: the unlucky albums pull the mean above the median.

In the drawing, the distribution is skewed to the right: most albums are completed with between 30 and 50 packets, but the long tail goes past 100. That is why the mean (43.74, the coral line) sits to the right of the median (42): the unlucky albums pull it. The last stickers are the expensive ones: when you are missing one, each packet only has a 10 % chance of bringing it.

Why the last stickers cost so much

That last sentence can be turned into a calculation. When you are only missing one sticker, each packet brings it with probability 5/50 = 0.1, the same as the gold one, and does not with 0.9. Waiting for that sticker is repeating an experiment until the first success: a geometric, the one from topic 3. Its expectation is 1/p = 1/0.1 = 10 packets.

So, of the 43.74 packets on average, about 10 go on the last sticker alone: almost a quarter of the collection for a single gap. With seed 42 it was 15, from 24 to 38: bad luck, but nothing unusual for a geometric.

And the other way round, at the start each packet brings almost everything new. That is why the tail of the histogram is so long: the albums that take a long time do not take it at the start, they take it waiting for the last two or three.

The same shows up with the other tail, the one to the right of the quantile:

mean(res > 60)   # P(needing more than 60 packets)

Output:

[1] 0.0895

A little under 9 in 100 albums need more than 60 packets. It fits the 90 % quantile: if with 60 you complete it at least 90 % of the time, more than 60 are needed at most 10 % of the time. The condition is the opposite one and its mean, just like with mean(res <= 45), is its estimated probability.

Common mistakes (with R’s real message)

Drawing more than there are without replacement.

sample(1:50, 60)

Output:

Error in sample.int(length(x), size, replace, prob) : cannot take a sample larger than the population when 'replace = FALSE'

“cannot take a sample larger than the population when ‘replace = FALSE'”: you cannot draw 60 different stickers out of 50. Either ask for fewer or set replace = TRUE if repeats make sense. Notice the error mentions sample.int: it is the internal function sample uses; the problem is in your call.

A probability vector that does not fit.

sample(0:2, 5, replace = TRUE, prob = c(0.7, 0.25))

Output:

Error in sample.int(length(x), size, replace, prob) : incorrect number of probabilities

“incorrect number of probabilities”: there are 3 values and 2 probabilities. Careful: if the probabilities do not add up to 1, sample does not complain, it rescales them silently. Check sum(p) == 1 yourself (or stopifnot(isTRUE(all.equal(sum(p), 1)))) if you want to catch a copying mistake.

Forgetting an argument of the d/p/q/r family.

rbinom(5, 0.1)

Output:

Error in rbinom(5, 0.1) : argument "prob" is missing, with no default

“argument “prob” is missing, with no default”: rbinom needs three things, n, size and prob, in that order. With two positional numbers, R has taken size = 0.1 and is missing prob. Naming the arguments (size =, prob =) avoids this mistake and makes the code clearer.

Asking for the probability of an impossible value.

dbinom(2.5, size = 20, prob = 0.1)

Output:

[1] 0
Warning message:
In dbinom(2.5, size = 20, prob = 0.1) :
  non-integer x = 2.500000

It returns 0 with a warning: “non-integer x = 2.500000”. A binomial cannot be 2.5. The warning saves you from a calculation mistake, but only if you read it; in a 1000-lap loop the warnings pile up at the end and they are easy to miss.

Filling in a loop a vector that does not exist.

rm(res_for)
for (i in 1:3) res_for[i] <- i^2

Output:

Error: object 'res_for' not found

“object ‘res_for’ not found”: to write into res_for[i] the vector has to exist first. Create it before the loop with numeric(3) (or with c() if you really do not know how many there will be).

Comparing your result with a classmate’s without having set the same seed (or with the seed set in different places). Two correct simulations give different numbers; what has to match is what they estimate, within a margin.

Try it in the R playground

Copy the script into the R playground on the site and run it. Careful: 2000 albums take a few seconds in the browser; if you want it faster, go down to 500.

packets_to_complete <- function(n_stickers = 50, per_packet = 5) {
  stopifnot(per_packet <= n_stickers)
  album <- rep(FALSE, n_stickers)
  packets <- 0
  while (!all(album)) {
    album[sample(n_stickers, per_packet)] <- TRUE
    packets <- packets + 1
  }
  packets
}

set.seed(100)
res <- replicate(2000, packets_to_complete())
summary(res)
mean(res <= 45)
hist(res, breaks = seq(20, 120, by = 5), main = "Packets to complete the album",
     xlab = "Packets", col = "#A99EF5", border = "white")
abline(v = mean(res), col = "#FF6B4A", lwd = 2)

What to look at:

  1. Run it twice in a row without the set.seed(100) line: the summary changes a little each time, but the mean stays close to 44.
  2. Change the packets to 10 stickers: replicate(2000, packets_to_complete(per_packet = 10)). Does it take half as many packets?
  3. In Environment, res is a num [1:2000] vector: click on it to see all of it.
  4. Type mean(res <= 60) and compare it with the 90 % quantile from the article.
  5. Try packets_to_complete(per_packet = 60) and read the stopifnot message.

Summary

PieceWhat forExample from the article
sample(x, n)draw without replacementa packet of 5 stickers
sample(x, n, replace = TRUE, prob = p)with replacement and with weightsshiny stickers
set.seed(k)make randomness repeatablethe same packet with 2026
replicate(n, expr)repeat an experiment2000 albums
for + numeric(n)the same, more flexibleidentical(res_for, res) is TRUE
mean(condition)estimated probabilitymean(res <= 45) = 0.6405
d/p/q/r + namethe distribution inside the codedbinom, dhyper, rbinom

Three ideas to take with you:

  1. A simulation is a function that does the experiment once, repeated many times. Write the function first, try it on a small case and only then repeat it.
  2. Set the seed right before each simulation that someone else (or you, tomorrow) has to be able to check.
  3. Simulating is for checking. If the simulated frequency does not look like the theoretical probability, one of the two is wrong: the model or the code.

What next?

In the R intensive 2 exercises it is your turn: simulate your own variables, compare with d/p/q/r, fix simulations that never end and the cheat sheet for the block.

Next, block 3: normal and joint distributions, where we leave loops behind to vectorise: doing in one line, and much faster, what we did here with a for loop.

Did this article help you? Here is how you can support SergioLearns →

Next step: exercisesR 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)Next block: ifelse, apply, sapply, pnorm and system.timeR intensive 3: normal and joint distributionsCheat sheet: the block on one page, to reviewCheat sheetScript: the block's functions, ready for your .RFor your script