Discrete random variables — R practice with a simulated WhatsApp group, waits for the useful message and a Poisson that fits the data (and the rgeom I thought was broken)
The first time I used rgeom() I got lots of zeros and thought it was broken: I had asked it “how many messages until the first useful one” and it answered 0 one time in five. It was not broken. R counts failures, not trials: a 0 means the first message was already useful. It took me half an afternoon to understand, and that is why this practice starts there: before you trust an output, you need to know what each function counts.
This practice puts to the test what you saw in the discrete random variables theory and its proofs. There are three medium-level programs, with the class WhatsApp group and made-up but realistic data: the first simulates ten thousand batches of ten messages and checks that the binomial gets it right; the second measures waits for the useful message with the geometric and the negative binomial; the third takes the messages counted in 60 ten-minute slots and checks whether a Poisson explains them. In all three, what matters is not the code, but how to read every number that comes out.
Table of Contents
Before you start
It helps to be clear about:
- The four functions
d,p,qandrof each model and what each one returns. - That in R the geometric and the negative binomial count failures before the success.
- That is written
1 - p…(k - 1, …). - The mean and variance of the binomial (, ), the geometric, the negative binomial and the Poisson ( and ).
If any of these sounds shaky, review the theory before carrying on.
The programs use set.seed() so that the simulation always gives the same result and you can compare your output with the one here. If you remove it, every run will give slightly different numbers, and that is a lesson too: that is how randomness behaves. All the code can be pasted into the site’s R playground or into RStudio.
Program 1: ten thousand batches of ten messages
Laura said that one in three messages in the group is a meme. If it is true (with ), the number of memes in ten messages is a . The program simulates 10,000 batches of ten messages, counts how many times each number of memes comes up and compares it with the theoretical mass function. What makes it tricky: there are values (9 and 10 memes) that almost never come up, and the table must have all eleven columns even if some stay at zero.
The idea
rbinom(10000, 10, 0.3)generates 10,000 numbers, each one the number of memes in a batch.table()counts how many times each value comes up. So that the values that do not appear also show up, it is first turned into a factor with levels 0 to 10.- Dividing by 10,000 gives relative frequencies, which are compared with
dbinom(0:10, 10, 0.3). - The mean and variance of the 10,000 values should look like and .
- While we are at it, we calculate the skewness coefficient the theory promised.
Before programming, think about what you expect to see: if the theory is right, the simulated row and the theoretical row will look alike in every column, and more so the more batches you simulate. If they do not, the mistake is in the code (or in the theory).
In plain words: each batch is a small experiment (read ten messages and count the memes) and the binomial tells you what share of the batches ends with each number. If , out of 10,000 batches about 2668 should end with three memes. With a few more values:
| Memes | Calculation | Expected batches | Why |
|---|---|---|---|
| 0 | 282.5 | none of the ten messages can be a meme | |
| 3 | 2668.3 | the most likely value: it matches the mean, | |
| 5 | 1029.2 | already in the tail, but still one batch in ten | |
| 9 | 1.4 | normally it comes up once, or twice, or not at all | |
| 10 | 0.06 | six batches in a million: almost certainly it does not come up |
The last row explains the factor line. With 10,000 batches, you would expect 10 not to come up even once, and table() does not invent columns for values it has not seen.
The code
set.seed(2026) # same simulation every time
n <- 10; p <- 0.3; batches <- 10000
memes <- rbinom(batches, n, p) # memes in each of the 10,000 batches
head(memes, 12) # the first 12, to see what is inside
# relative frequency of each value, with all 11 levels even if some do not appear
freq <- table(factor(memes, levels = 0:n)) / batches
comparison <- rbind(simulated = as.numeric(freq),
theoretical = dbinom(0:n, n, p))
colnames(comparison) <- 0:n
round(comparison, 3)
# mean and variance: simulated against the formulas
c(mean = mean(memes), np = n * p, var = var(memes), npq = n * p * (1 - p))
# the bet: at least 5 memes
c(simulated = mean(memes >= 5), theoretical = 1 - pbinom(4, n, p))
# skewness and kurtosis of a discrete variable from its table
shape <- function(x, px) {
m <- sum(x * px); s <- sqrt(sum((x - m)^2 * px))
c(skewness = sum((x - m)^3 * px) / s^3, kurtosis = sum((x - m)^4 * px) / s^4)
}
round(shape(0:n, dbinom(0:n, n, p)), 3) # the meme binomial
round(shape(0:3, c(0.4, 0.3, 0.2, 0.1)), 3) # "is there class tomorrow?"
barplot(comparison, beside = TRUE, col = c("grey", "tomato"),
legend.text = c("simulated", "theoretical"),
xlab = "Memes in 10 messages", ylab = "Relative frequency")
Two lines deserve a zoom. The first is the factor one:
freq <- table(factor(memes, levels = 0:n)) / batches
Without factor(…, levels = 0:n), if 10 memes never come up in the 10,000 batches, table() returns only ten columns and the comparison with dbinom(0:10, …), which has eleven, silently goes out of line. With the levels fixed, the column for 10 exists even if it is 0.
The second is mean(memes >= 5). memes >= 5 is a vector of TRUE and FALSE; the mean of a logical vector is the proportion of TRUE, because R treats them as 1 and 0. It is the shortest way to estimate a probability with a simulation.
Output
[1] 4 3 1 2 3 0 3 5 2 3 0 4
0 1 2 3 4 5 6 7 8 9 10
simulated 0.029 0.120 0.236 0.271 0.19 0.106 0.037 0.009 0.001 0 0
theoretical 0.028 0.121 0.233 0.267 0.20 0.103 0.037 0.009 0.001 0 0
mean np var npq
2.994400 3.000000 2.099979 2.100000
simulated theoretical
0.1535000 0.1502683
skewness kurtosis
0.276 2.876
skewness kurtosis
0.6 2.2
Checking two numbers by hand. The theoretical mean is and the variance, . And the probability of the bet, , matches the one in the theory.
The plot is what barplot(…, beside = TRUE) draws, redrawn in the site colours: each value has its pair of bars, the simulated one in grey and the theoretical one in coral. The pairs are almost twins for every value, which is what had to happen.
How to read it
head(memes, 12): each number is a batch of ten messages. There are batches with 0 memes and one with 5; 3, the most likely value, comes up in four of the twelve. A single batch says almost nothing.- The
comparisontable: in each column, thesimulatedrow is the proportion of batches with that number of memes andtheoreticalisdbinom. The differences are thousandths: with 10,000 batches the relative frequency is already very close to the probability (the idea from topic 2). In the column for 3, for example, the simulation gives 0.271 and the theory 0.267. mean,np,var,npq: the mean of the simulated data looks like 3 and the variance like 2.1. They are not exact because they come from a sample; if you repeat with another seed, they change in the second or third decimal.simulatedagainsttheoreticalin the bet: around 15% of the batches have five memes or more.shape: the meme binomial has skewness 0.276 (tail to the right, but not much) and kurtosis 2.876 (a bit less than 3). “Is there class tomorrow?” has skewness 0.6, more lopsided, and kurtosis 2.2: a flatter distribution, with only four values.
The skewness of “is there class tomorrow?”, sum by sum
shape() does four sums in two lines. With the small variable (0 to 3, with probabilities 0.4, 0.3, 0.2 and 0.1) you can see them one by one. First the mean: . Then each value with its distance to the mean raised to 2, 3 and 4, multiplied by its probability:
| Value | P | Distance | Squared · P | Cubed · P | Fourth power · P | Why |
|---|---|---|---|---|---|---|
| 0 | 0.4 | −1 | 0.4 | −0.4 | 0.4 | the most likely value is to the left of the mean: it subtracts in the cubed column |
| 1 | 0.3 | 0 | 0 | 0 | 0 | it sits exactly on the mean: it adds nothing |
| 2 | 0.2 | 1 | 0.2 | 0.2 | 0.2 | at distance 1, every power is the same |
| 3 | 0.1 | 2 | 0.4 | 0.8 | 1.6 | unlikely, but far away: cubed, it weighs twice as much as 0 |
| Sum | 1 | 1 | 0.6 | 2.2 | variance, third and fourth moment |
The variance is 1, so and dividing by or changes nothing: skewness 0.6 and kurtosis 2.2, as in the output. The key is the cubed column: 0 subtracts 0.4 and 3 adds 0.8. The value on the right is unlikely, but its distance cubed (2 becomes 8) wins, and the skewness comes out positive.
Check you’ve got it: if the probabilities were the same ones reversed (0.1, 0.2, 0.3 and 0.4), what skewness and kurtosis would shape() give?
The mean becomes , and the distances are −2, −1, 0 and 1. The variance is still . The cubed column gives : skewness −0.6, the same shape seen in a mirror, with the tail on the left. The kurtosis does not change, 2.2, because raising to the fourth power makes the sign of the distance disappear.
Questions you might ask
Why var(memes) and not the variance formula with probabilities? Because memes is data, not a table of probabilities. var() calculates the sample variance (dividing by ), as in topic 1. With 10,000 values, dividing by 10,000 or by 9,999 hardly changes anything.
Why does the column for 3 not give exactly 0.267? Because the simulation is a sample. With 10,000 batches, the standard error of a proportion around 0.27 is : differences of a few thousandths are to be expected.
What happens if I change batches to 100? The grey bars drift much further from the coral ones. Simulation converges slowly: to gain one decimal of precision you need a hundred times more batches.
What is the point of simulating something I can already calculate? To check that the formula (or your code) is right. In the exam it lets you verify a hand calculation in a minute, and later on it lets you calculate things that have no formula.
And what is shape for? To have and to hand for any variable given by its table. Notice that it uses probabilities, not data: it is the theoretical version.
Comparing table(memes) / batches with dbinom(0:10, …) without fixing the levels. If some value is missing from the simulation, the columns shift and you compare 9 with 10 without noticing.
Try it yourself
- Change
pto 0.5 and look at the skewnessshapereturns: it must be 0, because the binomial with is symmetric. - Simulate 20 messages instead of 10 and check that the mean becomes 6 and the variance 4.2.
Program 2: how much do you have to read until the useful message?
Only 20% of the messages have useful information about the assignment. How many useless ones do you have to read before the first useful one? And before collecting three useful ones? The program calculates probabilities and quantiles of the geometric and the negative binomial, clears up the difference between counting failures and trials, and checks the mean and variance of the negative binomial with a simulation. What makes it tricky: real questions are asked as “message number” (trials) and R answers in failures.
The idea
- Geometric with : probabilities from 0 to 6 useless ones, , the tail and the quantiles.
- Translate a question in trials (“the first useful one is message 3”) into failures (2 useless ones before).
- Negative binomial with : probabilities, mean, variance, quantiles and the mode.
- Simulate 5,000 reads with
rnbinom()to check the mean and the variance. - Plot the mass function of the negative binomial.
Before writing each line, say out loud what the variable counts. “Useless ones before the first useful one” is geometric; “the message where the first useful one arrives” is geometric plus 1.
In plain words: the two variables in the program count the same thing, useless messages, and they only differ in when you stop. The geometric stops at the first useful one and the negative binomial, at the third. Since the question almost never comes in failures, the first step is always to translate it:
| What the question says | Useless ones (what R counts) | Call | Why |
|---|---|---|---|
| the first useful one is message 1 | 0 | dgeom(0, p) | you did not have to read any useless one |
| the first useful one is message 3 | 2 | dgeom(2, p) | messages 1 and 2 were useless |
| the first useful one arrives by message 10 at the latest | at most 9 | pgeom(9, p) | if the useful one is message 10, there are 9 before it |
| the third useful one arrives at message 15 | 12 | dnbinom(12, 3, p) | of 15 messages, 3 are useful and the rest, useless |
The code
p <- 0.2 # 20% useful messages
# --- geometric: useless ones before the first useful one ---
round(dgeom(0:6, p), 4) # P(X = 0), ..., P(X = 6)
pgeom(9, p) # P(X <= 9): at most 9 useless ones
1 - pgeom(4, p) # P(X >= 5): at least 5 useless ones
(1 - p)^5 # the same with the tail formula
qgeom(c(0.5, 0.9), p) # median and 0.9 quantile
# trials against failures: "the first useful one is message number 3"
dgeom(2, p) # 2 useless ones before: correct
dgeom(3, p) # 3 useless ones before: message 4
# --- negative binomial: useless ones before the third useful one ---
r <- 3
round(dnbinom(0:5, r, p), 4)
c(mean = r * (1 - p) / p, var = r * (1 - p) / p^2)
qnbinom(c(0.5, 0.9), r, p)
pnbinom(10, r, p) # P(X <= 10)
(0:60)[which.max(dnbinom(0:60, r, p))] # the mode: the most likely value
set.seed(7)
waits <- rnbinom(5000, r, p) # 5,000 simulated reads
c(sim_mean = mean(waits), sim_var = var(waits))
plot(0:40, dnbinom(0:40, r, p), type = "h", lwd = 3,
xlab = "Useless before the third useful", ylab = "P(X = k)")
The mode line deserves an explanation:
(0:60)[which.max(dnbinom(0:60, r, p))]
dnbinom(0:60, r, p) gives 61 probabilities. which.max() returns the position of the largest (from 1 to 61), not the value of . That is why the position is used to index the vector 0:60, which does hold the values. Writing just which.max(…) would give the mode plus one, the same index offset as in the theory.
Output
[1] 0.2000 0.1600 0.1280 0.1024 0.0819 0.0655 0.0524 [1] 0.8926258 [1] 0.32768 [1] 0.32768 [1] 3 10 [1] 0.128 [1] 0.1024 [1] 0.0080 0.0192 0.0307 0.0410 0.0492 0.0551 mean var 12 60 [1] 11 22 [1] 0.4983478 [1] 7 sim_mean sim_var 12.09300 61.53426
Checking by hand: (the first message is already useful) and . The tail comes out the same with 1 - pgeom(4, p) and with the formula. The mean of the negative binomial is and its variance .
In the plot (the output of plot(…, type = "h") in the site colours) the negative binomial rises to 7 and 8 useless ones, which tie as the mode, and falls with a very long tail: the mean, 12, is to the right of the mode and the 0.9 quantile, 22, much further on. Three useful messages can occasionally cost you thirty useless ones.
How to read it
dgeom(0:6, p): 0.2 that the first message is already useful, 0.16 that there is one useless one before, and so on, falling by 20% each time. Each probability is the previous one times 0.8.pgeom(9, p)= 0.8926: almost nine times in ten you find the useful one before reading ten useless ones.1 - pgeom(4, p)and(1 - p)^5, both 0.32768: one time in three you read at least five useless ones. The two ways agree, which is what we proved in the proofs.qgeom(c(0.5, 0.9), p),3 10: half of the time you read 3 useless ones or fewer; 90% of the time, 10 or fewer.dgeom(2, p)= 0.128 againstdgeom(3, p)= 0.1024: if the first useful one is message 3, there were 2 useless ones before. Confusing them changes the answer by 20%.mean 12,var 60: on average, 12 useless ones before the third useful one, with a big spread (standard deviation ).qnbinom,11 22: half of the time 11 useless ones or fewer are enough; 90% of the time, 22 or fewer.pnbinom(10, r, p)= 0.4983: almost half of the time you collect the three useful ones reading at most ten useless ones.- The mode comes out as 7. In fact 7 and 8 tie (both are 0.0604):
which.max()returns the first maximum it finds. Both are below the mean, because the tail on the right pulls the mean up. sim_meanandsim_var: the 5,000 simulated reads stay close to 12 and 60.
The geometric, message by message
The first lines of the output, unfolded. Each row adds one more useless message before the useful one:
| Useless ones (k) | Calculation | dgeom | pgeom (cumulative) | Why |
|---|---|---|---|---|
| 0 | 0.2 | 0.2 | the first one is already useful | |
| 1 | 0.16 | 0.36 | one useless and then the useful one | |
| 2 | 0.128 | 0.488 | each extra useless one multiplies by 0.8 | |
| 3 | 0.1024 | 0.5904 | here the cumulative goes past 0.5: the median is 3 | |
| 4 | 0.0819 | 0.6723 | it keeps dropping by 20% each time |
You do not need to add up the cumulative. Not finding the useful one in the first messages means all are useless, so . For : , the pgeom(9, p) in the output. And this is how qgeom() works: it looks for the first where the cumulative reaches the probability you ask for. For 0.9, pgeom(9, p) = 0.8926 falls short and pgeom(10, p) = 0.9141 already gets there: that is why it gives 10.
Check you’ve got it: why does qgeom(0.5, p) give exactly 3, and not 2.5 or 3.2?
Because you cannot read 2.5 useless messages: the variable only takes whole numbers. qgeom() returns the smallest with . With the cumulative is 0.488, which does not reach it; with it is 0.5904, which already passes. There is nothing in between, so the median is 3.
Questions you might ask
Why is each geometric probability the previous one times 0.8? Because : going from to adds one more failure, which multiplies by .
How do I get the variable in trials in R? By adding 1: if X <- rgeom(…) counts failures, X + 1 counts the message number where the useful one arrives. Its mean is .
Why does the simulated variance move further from 60 than the mean from 12? The variance of a sample is less stable than the mean, especially with long tails: a few reads of 40 useless ones move the variance a lot.
Is the negative binomial with the geometric? Yes: dnbinom(k, 1, p) and dgeom(k, p) give the same. Try it with all.equal(dnbinom(0:10, 1, 0.2), dgeom(0:10, 0.2)).
Why is the mode 7 (or 8) and not 12? Because the distribution is not symmetric. The mean weighs in the large values of the tail; the mode only looks at which bar is tallest.
What would happen if one in four messages were useful (p = 0.25) instead of one in five?
Before running, the calculation. With the formulas, the mean of the negative binomial becomes and the variance .
p <- 0.25 # one in four messages, useful r <- 3 round(dgeom(0:3, p), 4) # starts at 0.25 and drops by 25% each time 1 - pgeom(4, p) # P(X >= 5): at least 5 useless ones c(mean = r * (1 - p) / p, var = r * (1 - p) / p^2) qnbinom(c(0.5, 0.9), r, p) # median and 0.9 quantile (0:60)[which.max(dnbinom(0:60, r, p))] # the mode set.seed(7) waits <- rnbinom(5000, r, p) # same seed as in program 2 c(sim_mean = mean(waits), sim_var = var(waits))
Output:
[1] 0.2500 0.1875 0.1406 0.1055 [1] 0.2373047 mean var 9 36 [1] 8 17 [1] 6 sim_mean sim_var 9.19800 36.62012
Compared with : the tail drops from 0.3277 to 0.2373, which is . The mean drops from 12 to 9 (25% less), but the variance drops from 60 to 36 (40% less), because is squared in its denominator. The quantiles go from 11 and 22 to 8 and 17. The mode comes out as 6, but 5 and 6 tie again (0.0779 both): this time which.max() picks 6 because the computer calculates it a tiny bit larger, in the 17th decimal place. Moral: look at the neighbouring bars before trusting which.max().
Passing R the message number instead of the number of failures. “The third useful one arrives at message 15” is useless ones: dnbinom(12, 3, 0.2), not dnbinom(15, 3, 0.2).
Try it yourself
- Calculate the probability that the first useful one arrives between message 3 and message 6 (both included). Hint: that is between 2 and 5 useless ones.
- Check memorylessness with a simulation: among the reads from
rgeom(100000, 0.2)that reach 6, what proportion reach 9? Compare it with .
Program 3: does a Poisson fit the group’s messages?
In deadline week I counted the group’s messages in 60 ten-minute slots, from 20:00 to 06:00 over several nights. Can a Poisson explain them? The program calculates the mean and variance of the 60 counts, fits a Poisson with equal to the mean, compares observed and expected frequencies and uses the model for two questions: the avalanche of eight or more messages and how many messages in an hour. What makes it tricky: the data come as a frequency table, not as a list.
| Messages in 10 minutes | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| Slots | 1 | 4 | 9 | 11 | 12 | 10 | 7 | 3 | 2 | 1 |
The idea
- Turn the frequency table into the 60 values with
rep(). - Estimate with the mean (in the Poisson, is the mean) and check that the variance is similar: in the Poisson they are equal.
- Expected frequencies: for each .
- Compare them in a table and in a bar chart.
- Use the model: and the change of interval to one hour ( times 6).
Before fitting, look at the mean and the variance. If the variance is twice the mean, no will work: the Poisson does not let them differ.
In plain words: “fitting a Poisson” means choosing its only parameter, , and asking how many slots of each kind you would have seen if the model were true. If is 0.1954, out of 60 slots you would expect about with four messages, and you counted 12. Doing that for each value and putting it next to what you counted is the whole fit: a column-by-column comparison.
The code
x <- 0:9 # messages in a slot
f <- c(1, 4, 9, 11, 12, 10, 7, 3, 2, 1) # number of slots with that value
messages <- rep(x, f) # the 60 counts, one per slot
length(messages)
lambda <- mean(messages) # estimate of lambda
c(mean = lambda, variance = var(messages))
expected <- 60 * dpois(x, lambda) # slots the model would expect
table_fit <- cbind(x, observed = f, expected = round(expected, 2))
table_fit
sum(expected) # short of 60: the tail of 10 or more is missing
# using the model
c(model = 1 - ppois(7, lambda), data = mean(messages >= 8))
c(hour_mean = 6 * lambda, P_over_30_in_an_hour = 1 - ppois(30, 6 * lambda))
barplot(rbind(f, expected), beside = TRUE, names.arg = x,
col = c("grey", "tomato"), legend.text = c("observed", "Poisson"),
xlab = "Messages in 10 minutes", ylab = "Slots")
The key line is rep(x, f). It repeats each value of x as many times as f says: 0 once, 1 four times, 2 nine times… That way the table turns back into the 60 original values and you can use mean() and var() as in topic 1. Without it you would have to calculate the mean with sum(x * f) / sum(f) by hand.
Output
[1] 60
mean variance
4.016667 3.745480
x observed expected
[1,] 0 1 1.08
[2,] 1 4 4.34
[3,] 2 9 8.72
[4,] 3 11 11.67
[5,] 4 12 11.72
[6,] 5 10 9.42
[7,] 6 7 6.30
[8,] 7 3 3.62
[9,] 8 2 1.82
[10,] 9 1 0.81
[1] 59.4987
model data
0.05213216 0.05000000
hour_mean P_over_30_in_an_hour
24.10000000 0.09952132
Checking the mean by hand: . And one expected frequency: , with .
The expected slots, row by row
The expected column comes from dpois(), but you can build it by hand with a trick: each Poisson probability is the previous one multiplied by . With :
| k | Calculation | P(X = k) | Expected (60 · P) | Why |
|---|---|---|---|---|
| 0 | 0.0180 | 1.08 | no arrivals: only is left | |
| 1 | 0.0724 | 4.34 | multiply by | |
| 2 | 0.1453 | 8.72 | is greater than 1: it keeps rising | |
| 3 | 0.1945 | 11.67 | : it rises less | |
| 4 | 0.1954 | 11.72 | : almost the same, this is the peak | |
| 5 | 0.1569 | 9.42 | is less than 1: from here on it drops |
That is why the mode of a Poisson is the integer part of : as long as does not go past , the factor is greater than 1 and the probability rises. Here it is 4, where the 12 slots of the tallest counted bar are.
Check you’ve got it: the expected values in the output add up to 59.4987. How many slots does the model expect with 10 messages or more?
What is missing to reach 60: , half a slot. It is the same as , which in R is 60 * (1 - ppois(9, lambda)) and gives 0.50. You counted none with 10 or more, and that is what the model says is normal.
In the plot, grey is what I counted and coral what the Poisson says. The pairs look alike for every value; where they differ most is at 6 (7 slots against 6.30 expected), and even there the difference is less than one slot.
How to read it
length(messages)= 60: all the data are there.mean 4.016667,variance 3.74548: the variance is a bit smaller than the mean, but of the same size. For a Poisson they must be similar, and they are. It is the first sign that the model may work.- The table: column by column, observed and expected differ by at most one slot. No column shouts “the Poisson fails here”.
sum(expected)= 59.5: the expected counts from 0 to 9 do not add up to 60 because the Poisson gives a little probability to 10, 11, 12… messages. If you run a formal test (you will see it in ME2), that tail is merged with the last column.modelagainstdatafor the avalanche: the model gives 5.2% of slots with eight or more messages; in the data it was 3 out of 60, 5%. Almost the same.- In an hour, messages on average, and more than 30 messages in an hour happens around 10% of the time.
Questions you might ask
Why do I estimate with the mean? Because in the Poisson . It is the idea behind the method of moments, which you will see in topic 9: set the theoretical moment equal to the sample one.
When would I say the Poisson does not fit? If the variance is much bigger than the mean (overdispersion: very quiet slots and others with avalanches), or if the shape of the observed bars does not look like the expected one. In that case a negative binomial, whose variance is bigger than its mean, usually works better.
Why do I multiply by 6 for an hour? Because an hour is six ten-minute slots and, if messages arrive at a constant rate, the means add up: . The sum of independent Poissons is Poisson.
Is it true that messages arrive at a constant rate all night? Probably not: at 23:55 on deadline night there are more than at 4:00. For a finer model you would have to split by time slot. A model is a useful simplification, not the truth.
Calculating the mean of the table with mean(f). That is the mean of the frequencies (6 slots per value), not the mean number of messages. With frequency tables, either rep(x, f) or sum(x * f) / sum(f).
Try it yourself
- Change the data to create overdispersion (for example,
f <- c(8, 6, 6, 5, 4, 5, 6, 6, 6, 8)) and watch the variance shoot up and the bars stop looking alike. - Use the model to calculate the probability that between 10 and 15 messages (both included) arrive in 30 minutes.
Common mistakes in this practice
- Comparing misaligned tables.
table()withoutfactor(…, levels = …)skips the values that do not appear. - Passing trials where R expects failures in
dgeomanddnbinom. - Using
which.max()as if it returned the value. It returns the position; with values starting at 0, the mode is the position minus one. mean(f)with a frequency table. The mean issum(x * f) / sum(f).- Changing the interval without changing in the Poisson.
- Expecting a simulation to give the exact value. It gives an approximation that improves slowly with the number of repetitions.
Try it in the R playground
Open the site’s R playground (or RStudio) and try this short version of the three programs:
set.seed(1) memes <- rbinom(2000, 10, 0.3) barplot(table(factor(memes, levels = 0:10)) / 2000) useful <- rgeom(2000, 0.2) table(useful)[1:5] arrivals <- rpois(2000, 4) c(mean = mean(arrivals), variance = var(arrivals))
What to look at:
- In Environment you will see
memes,usefulandarrivals, each with 2,000 values. Click on them to see them. - The plot is the simulated binomial: it looks like the one in program 1, but more irregular (2,000 batches instead of 10,000).
table(useful)[1:5]starts at 0: proof thatrgeomcounts failures.- In
arrivals, mean and variance both come out close to 4: the Poisson’s fingerprint. - Type
?rnbinomand look at themuargument: the negative binomial can also be given by its mean instead ofprob.
Summary
- A simulation with
r…andtable()checks a mass function: with many repetitions, the relative frequency approachesd…. mean(x >= k)estimates in a simulation;1 - p…(k - 1, …)calculates it exactly.- R’s geometric and negative binomial count failures: the message number is failures plus successes.
- The mode is found with
which.max(), remembering that it returns a position. - To fit a Poisson, = the mean of the data; if the variance does not look like the mean, be suspicious.
- Changing the interval in the Poisson means multiplying .
Checklist: have you practised it?
- Have you run the three programs and checked the outputs?
- Do you know why the table in program 1 needs
factor(…, levels = 0:10)? - Could you translate “the first useful one arrives at message 7” into a call to
dgeom? - Can you explain in your own words why the mode of the negative binomial is smaller than its mean, and why
which.max()only gives you one of the two modes? - Do you know what to look at first to decide whether a Poisson fits some counts?
- Have you tried the “Try it yourself” sections without looking at the theory?
If you answered yes to almost everything, you are ready for the discrete random variables exercises, where I no longer give you the code: exam-style exercises with their marks, to do on paper and with R. See you there!
Next step: exercisesDiscrete random variables — exam-style exercises with the WhatsApp group, models you have to recognise and a mass function with a parameter (and the 1 – pbinom(5) that cost me a point)Did this article help you? Here is how you can support SergioLearns →



