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.

Before you start

It helps to be clear about:

  • The four functions d, p, q and r of each model and what each one returns.
  • That in R the geometric and the negative binomial count failures before the success.
  • That P(X≥k)P(X \geq k) is written 1 - p…(k - 1, …).
  • The mean and variance of the binomial (npnp, np(1−p)np(1-p)), the geometric, the negative binomial and the Poisson (λ\lambda and λ\lambda).

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 p=0.3p = 0.3), the number of memes in ten messages is a Binom(10,0.3)\text{Binom}(10, 0.3). 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

  1. rbinom(10000, 10, 0.3) generates 10,000 numbers, each one the number of memes in a batch.
  2. 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.
  3. Dividing by 10,000 gives relative frequencies, which are compared with dbinom(0:10, 10, 0.3).
  4. The mean and variance of the 10,000 values should look like np=3np = 3 and np(1−p)=2.1np(1-p) = 2.1.
  5. 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 P(X=3)=0.2668 P(X = 3) = 0.2668 , out of 10,000 batches about 2668 should end with three memes. With a few more values:

MemesCalculationExpected batchesWhy
010000⋅0.710 10000 \cdot 0.7^{10} 282.5none of the ten messages can be a meme
310000⋅0.2668 10000 \cdot 0.2668 2668.3the most likely value: it matches the mean, np=3 np = 3
510000⋅0.1029 10000 \cdot 0.1029 1029.2already in the tail, but still one batch in ten
910000⋅0.000138 10000 \cdot 0.000138 1.4normally it comes up once, or twice, or not at all
1010000⋅0.310 10000 \cdot 0.3^{10} 0.06six 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 10⋅0.3=310 \cdot 0.3 = 3 and the variance, 10⋅0.3⋅0.7=2.110 \cdot 0.3 \cdot 0.7 = 2.1. And the probability of the bet, 1−0.8497=0.15031 – 0.8497 = 0.1503, matches the one in the theory.

barplot(beside = TRUE): 10,000 simulated batches against the binomialPairs of bars from 0 to 10 memes: relative frequency of 10,000 simulated batches in grey and binomial probability with n 10 and p 0.3 in coral. At 3, 0.271 against 0.267; at 4, 0.190 against 0.200. The other pairs are almost equal.0.000.100.200.30012345678910Memes in 10 messagesRelative frequencysimulatedtheoretical
Redrawn in the site colours: with 10,000 batches, simulation and theory are almost indistinguishable.

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 comparison table: in each column, the simulated row is the proportion of batches with that number of memes and theoretical is dbinom. 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.
  • simulated against theoretical in 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: m=0⋅0.4+1⋅0.3+2⋅0.2+3⋅0.1=0+0.3+0.4+0.3=1 m = 0 \cdot 0.4 + 1 \cdot 0.3 + 2 \cdot 0.2 + 3 \cdot 0.1 = 0 + 0.3 + 0.4 + 0.3 = 1 . Then each value with its distance to the mean raised to 2, 3 and 4, multiplied by its probability:

ValuePDistanceSquared · PCubed · PFourth power · PWhy
00.4−10.4−0.40.4the most likely value is to the left of the mean: it subtracts in the cubed column
10.30000it sits exactly on the mean: it adds nothing
20.210.20.20.2at distance 1, every power is the same
30.120.40.81.6unlikely, but far away: cubed, it weighs twice as much as 0
Sum110.62.2variance, third and fourth moment

The variance is 1, so s=1 s = 1 and dividing by s3 s^3 or s4 s^4 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 0⋅0.1+1⋅0.2+2⋅0.3+3⋅0.4=2 0 \cdot 0.1 + 1 \cdot 0.2 + 2 \cdot 0.3 + 3 \cdot 0.4 = 2 , and the distances are −2, −1, 0 and 1. The variance is still 4⋅0.1+1⋅0.2+0+1⋅0.4=1 4 \cdot 0.1 + 1 \cdot 0.2 + 0 + 1 \cdot 0.4 = 1 . The cubed column gives −0.8−0.2+0+0.4=−0.6 -0.8 – 0.2 + 0 + 0.4 = -0.6 : 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 n−1n – 1), 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 0.27⋅0.73/10000≈0.0044\sqrt{0.27 \cdot 0.73 / 10000} \approx 0.0044: 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 α3\alpha_3 and α4\alpha_4 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 p to 0.5 and look at the skewness shape returns: it must be 0, because the binomial with p=0.5p = 0.5 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

  1. Geometric with p=0.2p = 0.2: probabilities from 0 to 6 useless ones, P(X≤9)P(X \leq 9), the tail P(X≥5)P(X \geq 5) and the quantiles.
  2. Translate a question in trials (“the first useful one is message 3”) into failures (2 useless ones before).
  3. Negative binomial with r=3r = 3: probabilities, mean, variance, quantiles and the mode.
  4. Simulate 5,000 reads with rnbinom() to check the mean and the variance.
  5. 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 saysUseless ones (what R counts)CallWhy
the first useful one is message 10dgeom(0, p)you did not have to read any useless one
the first useful one is message 32dgeom(2, p)messages 1 and 2 were useless
the first useful one arrives by message 10 at the latestat most 9pgeom(9, p)if the useful one is message 10, there are 9 before it
the third useful one arrives at message 1512dnbinom(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 kk. 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: P(X=0)=0.2P(X = 0) = 0.2 (the first message is already useful) and P(X=1)=0.8⋅0.2=0.16P(X = 1) = 0.8 \cdot 0.2 = 0.16. The tail P(X≥5)=0.85=0.32768P(X \geq 5) = 0.8^5 = 0.32768 comes out the same with 1 - pgeom(4, p) and with the formula. The mean of the negative binomial is 3⋅0.8/0.2=123 \cdot 0.8 / 0.2 = 12 and its variance 3⋅0.8/0.04=603 \cdot 0.8 / 0.04 = 60.

plot(type = "h"): negative binomial with r = 3 and p = 0.2Bars of the negative binomial from 0 to 40. The highest, in coral, are 7 and 8 with 0.0604 each. Dashed line at the mean, 12, and a green one at the 0.9 quantile, 22. The tail goes on beyond 30.0.000.020.040.060510152025303540Useless before the third usefulP(X = k)modes 7 and 8mean 120.9 quantile: 22
Redrawn in the site colours: the mode comes before the mean, and the tail is so long that 10% of the time you go past 22 useless ones.

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 against dgeom(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 60≈7.75\sqrt{60} \approx 7.75).
  • 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_mean and sim_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)Calculationdgeompgeom (cumulative)Why
00.2 0.2 0.20.2the first one is already useful
10.8⋅0.2 0.8 \cdot 0.2 0.160.36one useless and then the useful one
20.82⋅0.2 0.8^2 \cdot 0.2 0.1280.488each extra useless one multiplies by 0.8
30.83⋅0.2 0.8^3 \cdot 0.2 0.10240.5904here the cumulative goes past 0.5: the median is 3
40.84⋅0.2 0.8^4 \cdot 0.2 0.08190.6723it keeps dropping by 20% each time

You do not need to add up the cumulative. Not finding the useful one in the first k+1 k + 1 messages means all k+1 k + 1 are useless, so P(X≤k)=1−0.8k+1 P(X \leq k) = 1 – 0.8^{k+1} . For k=9 k = 9 : 1−0.810=1−0.1074=0.8926 1 – 0.8^{10} = 1 – 0.1074 = 0.8926 , the pgeom(9, p) in the output. And this is how qgeom() works: it looks for the first k k 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 k k with P(X≤k)≥0.5 P(X \leq k) \geq 0.5 . With k=2 k = 2 the cumulative is 0.488, which does not reach it; with k=3 k = 3 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 P(X=k)=0.8k⋅0.2P(X = k) = 0.8^k \cdot 0.2: going from kk to k+1k + 1 adds one more failure, which multiplies by 1−p1 – p.

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 4+1=5=1/p4 + 1 = 5 = 1/p.

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 r=1r = 1 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 3⋅0.75/0.25=9 3 \cdot 0.75 / 0.25 = 9 and the variance 3⋅0.75/0.252=36 3 \cdot 0.75 / 0.25^2 = 36 .

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 p=0.2 p = 0.2 : the tail P(X≥5) P(X \geq 5) drops from 0.3277 to 0.2373, which is 0.755 0.75^5 . The mean drops from 12 to 9 (25% less), but the variance drops from 60 to 36 (40% less), because p p 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 15−3=1215 – 3 = 12 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 0.830.8^3.

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 λ\lambda 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 minutes0123456789
Slots1491112107321

The idea

  1. Turn the frequency table into the 60 values with rep().
  2. Estimate λ\lambda with the mean (in the Poisson, λ\lambda is the mean) and check that the variance is similar: in the Poisson they are equal.
  3. Expected frequencies: 60⋅P(X=k)60 \cdot P(X = k) for each kk.
  4. Compare them in a table and in a bar chart.
  5. Use the model: P(X≥8)P(X \geq 8) and the change of interval to one hour (λ\lambda times 6).

Before fitting, look at the mean and the variance. If the variance is twice the mean, no λ\lambda will work: the Poisson does not let them differ.

In plain words: “fitting a Poisson” means choosing its only parameter, λ \lambda , and asking how many slots of each kind you would have seen if the model were true. If P(X=4) P(X = 4) is 0.1954, out of 60 slots you would expect about 60⋅0.1954≈11.72 60 \cdot 0.1954 \approx 11.72 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: 0⋅1+1⋅4+2⋅9+3⋅11+4⋅12+5⋅10+6⋅7+7⋅3+8⋅2+9⋅160=24160=4.0167\frac{0 \cdot 1 + 1 \cdot 4 + 2 \cdot 9 + 3 \cdot 11 + 4 \cdot 12 + 5 \cdot 10 + 6 \cdot 7 + 7 \cdot 3 + 8 \cdot 2 + 9 \cdot 1}{60} = \frac{241}{60} = 4.0167. And one expected frequency: 60⋅P(X=4)=60⋅0.1954≈11.7260 \cdot P(X = 4) = 60 \cdot 0.1954 \approx 11.72, with λ=4.0167\lambda = 4.0167.

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 λ/k \lambda / k . With λ=4.0167 \lambda = 4.0167 :

kCalculationP(X = k)Expected (60 · P)Why
0e−4.0167 e^{-4.0167} 0.01801.08no arrivals: only e−λ e^{-\lambda} is left
10.0180⋅4.0167/1 0.0180 \cdot 4.0167 / 1 0.07244.34multiply by λ/1 \lambda / 1
20.0724⋅4.0167/2 0.0724 \cdot 4.0167 / 2 0.14538.72λ/2 \lambda / 2 is greater than 1: it keeps rising
30.1453⋅4.0167/3 0.1453 \cdot 4.0167 / 3 0.194511.67λ/3≈1.34 \lambda / 3 \approx 1.34 : it rises less
40.1945⋅4.0167/4 0.1945 \cdot 4.0167 / 4 0.195411.72λ/4≈1.004 \lambda / 4 \approx 1.004 : almost the same, this is the peak
50.1954⋅4.0167/5 0.1954 \cdot 4.0167 / 5 0.15699.42λ/5 \lambda / 5 is less than 1: from here on it drops

That is why the mode of a Poisson is the integer part of λ \lambda : as long as k k does not go past λ \lambda , 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: 60−59.4987=0.50 60 – 59.4987 = 0.50 , half a slot. It is the same as 60⋅(1−P(X≤9)) 60 \cdot (1 – P(X \leq 9)) , 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.

barplot(beside = TRUE): observed slots against the PoissonPairs of bars from 0 to 9 messages: observed slots in grey (1, 4, 9, 11, 12, 10, 7, 3, 2 and 1) and expected ones with a Poisson of mean 4.02 in coral (1.08, 4.34, 8.72, 11.67, 11.72, 9.42, 6.30, 3.62, 1.82 and 0.81).024681012140123456789Messages in 10 minutesSlotsobservedPoisson
Redrawn in the site colours: for no value do observed and expected differ by a whole slot.

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.
  • model against data for 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, λ=6⋅4.0167=24.1\lambda = 6 \cdot 4.0167 = 24.1 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 λ\lambda with the mean? Because in the Poisson E(X)=λE(X) = \lambda. 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 λ\lambda 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: 6λ6\lambda. 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() without factor(…, levels = …) skips the values that do not appear.
  • Passing trials where R expects failures in dgeom and dnbinom.
  • 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 is sum(x * f) / sum(f).
  • Changing the interval without changing λ\lambda 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:

  1. In Environment you will see memes, useful and arrivals, each with 2,000 values. Click on them to see them.
  2. The plot is the simulated binomial: it looks like the one in program 1, but more irregular (2,000 batches instead of 10,000).
  3. table(useful)[1:5] starts at 0: proof that rgeom counts failures.
  4. In arrivals, mean and variance both come out close to 4: the Poisson’s fingerprint.
  5. Type ?rnbinom and look at the mu argument: the negative binomial can also be given by its mean instead of prob.

Summary

  • A simulation with r… and table() checks a mass function: with many repetitions, the relative frequency approaches d….
  • mean(x >= k) estimates P(X≥k)P(X \geq k) 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, λ\lambda = the mean of the data; if the variance does not look like the mean, be suspicious.
  • Changing the interval in the Poisson means multiplying λ\lambda.

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 →