R intensive 5: estimation and intervals — optimize, optim and your own interval function with the goals of the campus league (and the 95 % that was right 87 % of the time)
A function that computes a confidence interval is not finished until you check that it delivers what it promises. I found out while preparing for EC2: I had a lovely function for the interval of a Poisson, the one from the notes, and out of curiosity I simulated how often it contained the true value. With large samples, 95 % of the time, as it should. With 10 values and a small mean, 87 %. The formula was not copied wrong: it is an approximation, and with little data it fails. The simulation took four lines to tell me.
This is the fifth and last block of the intensive. Point estimation, the properties of estimators and confidence intervals are in ME1 topics 9, 10 and 11. Here we program them: write the log-likelihood as a function, find its maximum with optimize and optim, write functions that return an interval with their checks, measure their real coverage by simulating and, to finish, organise the exam script.
In a nutshell: in R, maximum likelihood is programmed by writing the log-likelihood as a function of the parameter and finding its maximum with optimize (one parameter) or optim (several, minimising minus the log-likelihood). A confidence interval is programmed as a function that checks the data and returns a list; its real coverage is measured by simulating many samples with the parameter known.
Table of Contents
Before you start. From R you need what the earlier blocks of the intensive covered: writing a function, applying it to many values with sapply, repeating a simulation with replicate and knowing that the mean of a vector of TRUE/FALSE is a proportion. From statistics, three ideas from ME1 topics 9 and 11, which we review with the goals as they come up: the likelihood (how probable your data are for each value of the parameter), the maximum likelihood estimator (the value that makes them most probable) and the confidence interval (a range computed with a method that is right a fixed percentage of the time). The article has three parts, in this order. First, the pieces: the log-likelihood as a function and its maximum, with optimize for one parameter and with optim for two. Then, the complete program: an interval function written four times, each one better than the last, and checked with its coverage. Finally, how to organise the exam script and the common mistakes. If you get lost, go back to the league: 30 matches, 5.77 goals on average and the question of between which values the true mean lies.
What you are going to program (and for which topic)
The example: the campus futsal league. I wrote down the total goals of the 30 matches of the first half of the season (there is no goalless match in futsal) and, in 20 of them, the minutes it took for the first goal to arrive.
# Total goals in the 30 matches of the campus futsal league
goals <- c(5, 7, 4, 6, 8, 3, 6, 5, 9, 4, 6, 7, 5, 2, 6,
8, 5, 7, 4, 6, 10, 5, 6, 3, 7, 5, 6, 8, 4, 6)
c(n = length(goals), mean = mean(goals), variance = round(var(goals), 2))
Output:
n mean variance 30.000000 5.766667 3.290000
Thirty matches with 5.77 goals on average. The goals in a match are the classic example of a Poisson: events that arrive one at a time, at a roughly constant rate. (The variance, 3.29, being smaller than the mean says it is not a perfect Poisson; for practising the code, it will do.)
What you are going to build:
- The Poisson log-likelihood as a function of λ, its chart and its maximum with
optimize. - The maximum likelihood of a two-parameter gamma with
optim, with and without bounds. - A
ci_poisson()function with a confidence level, checks and two methods. - A function that measures the real coverage of the interval by simulating.
- The skeleton of the exam script, organised by exercise.
The R pieces you need
Before the code: the likelihood of three matches, by hand
Before writing loglik, let’s do by hand what it will do inside. With all 30 matches there are too many sums, so we use only the first three: 5, 7 and 4 goals.
The question the likelihood answers is this: if the mean number of goals per match were λ, what would be the probability of getting exactly what we got? Careful, it is not the probability of λ. It is the probability of your data, assuming a λ. And it is used to compare: the λ that gives the most probability to what you have seen is the best candidate.
Let’s try λ = 5. Each match is a Poisson(5) and the matches are independent, so the probability of seeing 5, 7 and 4 is the product of three probabilities. R gives them with dpois:
# The likelihood of the first three matches, by hand three <- goals[1:3] # 5, 7 and 4 goals round(dpois(three, 5), 4) # probability of each value if lambda = 5 round(log(dpois(three, 5)), 4) # its logarithm sum(log(dpois(three, 5))) # the log-likelihood with lambda = 5 sum(log(dpois(three, 6))) # and with lambda = 6
Output:
[1] 0.1755 0.1044 0.1755 [1] -1.7403 -2.2591 -1.7403 [1] -5.7397 [1] -5.822555
| Step | Calculation | Why |
|---|---|---|
| 1 | P(X = 5) = 0.1755; P(X = 7) = 0.1044; P(X = 4) = 0.1755 | dpois(three, 5): the probability of each value in a Poisson(5) |
| 2 | L(5) = 0.1755 · 0.1044 · 0.1755 = 0.0032 | the matches are independent: the probability of all three at once is the product |
| 3 | log L(5) = −1.7403 − 2.2591 − 1.7403 = −5.7397 | the logarithm of a product is the sum of the logarithms |
| 4 | log L(6) = −5.8226 | the same, with λ = 6 |
| 5 | −5.7397 > −5.8226 | λ = 5 makes these three matches more probable than λ = 6 |
Look at step 5: with these three matches λ = 5 wins, and with all 30 (you will see it in a moment) λ = 6 wins. It is not a contradiction. The mean of these three is 16 / 3 = 5.33, closer to 5; the mean of the 30 is 5.77, closer to 6. The likelihood rewards the values of λ close to what you have seen.
And why the logarithm, if the product already works? For two reasons. One: sums are much easier to differentiate than products, which is exactly what you do by hand in topic 9. Two: with 30 values the product is already a tiny number, and with hundreds the computer leaves it at 0. Since the logarithm is increasing, the λ that maximises the product also maximises the sum: the maximum is in the same place.
Now then: loglik is steps 1 and 3 in one line. The only difference is that it puts log = TRUE inside dpois instead of log(…) outside, which gives the same and never goes through the tiny product.
Check you’ve got it: with only these three matches, which λ gives the highest log-likelihood? What is its value there?
λ = 16 / 3 = 5.33, the mean of the three. The maximum likelihood estimator of a Poisson is the sample mean, and that holds for 3 values just as for 30.
There the log-likelihood is −5.7071 (in R: loglik(16/3, three)). It is higher than with λ = 5 (−5.7397) and with λ = 6 (−5.8226), as it had to be: no other λ makes those three matches more probable.
The log-likelihood as a function
In topic 9 the likelihood is written by hand and differentiated. In R it is enough to write it as a function of the parameter, with the data as the second argument:
# The log-likelihood of a Poisson, as a function of lambda loglik <- function(lambda, x) sum(dpois(x, lambda, log = TRUE)) loglik(5, goals) loglik(6, goals) sapply(c(5, 5.5, 5.8, 6, 6.5), loglik, x = goals)
Output:
[1] -63.73578 [1] -62.19415 [1] -63.73578 -62.24712 -62.05912 -62.19415 -63.34676
dpois(x, lambda, log = TRUE) gives the logarithm of the probability of each value, and sum adds them up: that is log L(λ). With λ = 5 it is −63.74 and with λ = 6, −62.19: the data are more likely with 6 than with 5. The third line evaluates it at five values at once: the highest is the one at 5.8, the closest to the mean.
Note the sapply call: sapply(values, loglik, x = goals). Each value goes in as the first argument of loglik (lambda), and whatever you write after the function name (x = goals) is passed unchanged in every call. It is the way to fix the data without writing an anonymous function.
What sapply does inside, call by call:
| Value | Call R makes | Result | Why |
|---|---|---|---|
| 5 | loglik(5, x = goals) | −63.74 | the value goes into the first free argument of loglik, which is lambda |
| 5.5 | loglik(5.5, x = goals) | −62.25 | x = goals is repeated unchanged in every call |
| 5.8 | loglik(5.8, x = goals) | −62.06 | the highest: 5.8 is the value closest to the mean, 5.77 |
| 6 | loglik(6, x = goals) | −62.19 | 0.23 away from the mean: a little lower than 5.8 |
| 6.5 | loglik(6.5, x = goals) | −63.35 | far from the mean on the high side: it drops again |
And why not write loglik(c(5, 6), goals) directly? Because it does not give two values:
loglik(c(5, 6), goals) # the log-likelihood at 5 and at 6?
Output:
[1] -63.78541
Passing several λ at once to loglik. There is no error and no warning: you get a single number, −63.79, which is neither the one for 5 (−63.74) nor the one for 6 (−62.19). Inside, dpois(goals, c(5, 6)) recycles the vector of λ: the first match is evaluated with 5, the second with 6, the third with 5 again… and sum lumps everything into a meaningless number. A function that adds up inside works with one λ at a time; for several, sapply.
Always use log = TRUE and add; never multiply the probabilities with prod. With a lot of data the product becomes so small that the computer rounds it to 0 (you will see it in the common mistakes), and then every value of the parameter looks equally bad.
Drawing it is the first thing worth doing before looking for a maximum:
curve(sapply(x, loglik, x = goals), from = 4, to = 8,
main = "Log-likelihood of the goals", xlab = "lambda", ylab = "log L")
abline(v = mean(goals), lty = 2, col = "#FF6B4A")
In the drawing, the curve goes up, reaches a maximum and comes down: a single peak, right above the dashed line of the mean, 5.77. That is what topic 9 says (the maximum likelihood estimator of λ is the sample mean), seen without differentiating. A code detail: curve calls its expression with a vector of x values, and loglik can only work with one λ at a time (inside it adds everything up); that is why the expression is sapply(x, loglik, x = goals) and not loglik(x, goals). The x of curve and the x = of loglik are different things: the first is the axis, the second, the argument holding the data.
optimize: the maximum of one parameter
optimize(f, interval, …) finds the minimum of f in an interval; with maximum = TRUE, the maximum:
# optimize: the maximum of a one-parameter function in an interval opt <- optimize(loglik, interval = c(0.1, 20), x = goals, maximum = TRUE) opt round(opt$maximum, 4)
Output:
$maximum [1] 5.766671 $objective [1] -62.05624 [1] 5.7667
It returns a list with two things: $maximum, the λ where the maximum is (5.766671), and $objective, the value of the log-likelihood there (−62.056). The mean was 5.766667: they match to the fifth decimal. The difference is the algorithm’s tolerance: optimize does not compute the derivative, it keeps narrowing the interval until it is smaller than a tolerance, and stops there.
Check you’ve got it: what does optimize(loglik, interval = c(6, 20), x = goals, maximum = TRUE) return?
About 6 (6.000043, to be precise): the left edge of the interval. The real maximum, 5.77, has been left outside, and within [6, 20] the log-likelihood only goes down. The highest thing it finds is stuck to 6.
optimize gives no warning: it searches where you tell it to. That is why it is worth drawing the curve first (or looking at where the mean falls) and giving an interval that leaves the maximum well inside. It is the same hint you will see in the common mistakes: an estimate stuck to one end of the interval is suspicious.
optim: several parameters at once
For the minutes until the first goal we use a gamma, which has two parameters (shape and rate). optimize only handles one; for two or more there is optim, which minimises. That is why we give it minus the log-likelihood (nll, negative log-likelihood):
# Minutes until the first goal in 20 matches: two parameters, optim
first_goal <- c(2.1, 5.4, 0.8, 3.9, 7.2, 1.5, 4.4, 2.8, 9.6, 3.1,
1.2, 6.3, 2.5, 4.9, 3.6, 0.6, 5.8, 2.2, 8.1, 3.3)
nll_gamma <- function(par, x) { # minus the log-likelihood
-sum(dgamma(x, shape = par[1], rate = par[2], log = TRUE))
}
o <- optim(c(1, 1), nll_gamma, x = first_goal, method = "L-BFGS-B", lower = c(1e-6, 1e-6))
round(o$par, 4)
o$convergence
Output:
[1] 2.3416 0.5906 [1] 0
How to talk to optim:
- The parameters go in a single vector,
par. The function takes them out withpar[1]andpar[2]. - The first argument of
optimis the starting point (c(1, 1)): it starts searching from there. method = "L-BFGS-B"withlowerstops it from trying negative values, which make no sense in a gamma.$convergence= 0 means it finished properly. Any other number is a warning: always look at it.
The estimated shape is 2.3416 and the rate, 0.5906 (per minute). With them, the model’s mean is shape / rate = 2.3416 / 0.5906 = 3.96 minutes; the data’s is 3.965. The model fits the data.
The log-scale trick
There is another way to rule out negative values, which needs no lower and works with any method: search over the logarithms of the parameters. If optim moves lpar across all real numbers, exp(lpar) is always positive:
# Same problem, no bounds: optimise on the log scale nll_gamma_log <- function(lpar, x) nll_gamma(exp(lpar), x) o2 <- optim(c(0, 0), nll_gamma_log, x = first_goal) round(exp(o2$par), 4) round(c(o$value, o2$value), 4)
Output:
[1] 2.3411 0.5905 [1] 44.2585 44.2585
nll_gamma_log is a one-line function that wraps the other one. The starting point c(0, 0) on the log scale is c(1, 1) on the normal one (e⁰ = 1). Without a method, optim uses Nelder-Mead, which needs no derivatives. The estimates (2.3411 and 0.5905) match the previous ones to the third decimal, and the minimum value ($value, 44.2585) is the same: both found the same point.
The drawing shows the idea of optim: a map of the function with its levels and the algorithm going down from the starting point to the bottom of the valley. The starting point matters: if you start very far away, or the function has several valleys, it may end up somewhere else. That is why it is worth starting from something sensible (for example, the method-of-moments estimates).
A sensible starting point: the method of moments
The previous paragraph recommends starting from the method-of-moments estimates. This is how they are computed for the gamma, with the minutes until the first goal.
The idea of the method (topic 9) is to match what the model says to what the data say. A gamma with shape a and rate b has mean a / b and variance a / b². The data have mean 3.965 and variance 6.20. That is two equations with two unknowns:
| Step | Calculation | Why |
|---|---|---|
| 1 | a / b = 3.965 | the model’s mean, equal to the data’s |
| 2 | a / b² = 6.20 | the model’s variance, equal to the data’s |
| 3 | b = 3.965 / 6.20 = 0.64 | divide equation 1 by equation 2: (a / b) / (a / b²) = b |
| 4 | a = 3.965 · 0.64 = 2.54 | solve equation 1 for a; together with step 3, a = mean² / variance |
In R it is two lines, and the result goes straight into optim as the starting point:
# Starting point from the method of moments
m <- mean(first_goal)
v <- var(first_goal)
start <- c(m^2 / v, m / v) # shape = mean²/var, rate = mean/var
round(start, 4)
o3 <- optim(start, nll_gamma, x = first_goal, method = "L-BFGS-B",
lower = c(1e-6, 1e-6))
round(o3$par, 4) # the same maximum as from c(1, 1)
c(from_1_1 = o$counts[[1]], from_moments = o3$counts[[1]])
Output:
[1] 2.5369 0.6398
[1] 2.3416 0.5906
from_1_1 from_moments
14 8
From (2.54; 0.64), optim gets to the same place as from (1, 1): 2.3416 and 0.5906. What changes is the path. $counts counts how many times optim has called nll_gamma, and from the moments it needs 8 instead of 14. With two parameters and 20 values you do not notice it, but with harder functions, starting close is what separates reaching the right valley from getting lost in another one.
Notice too that the moments do not give the same as maximum likelihood (a shape of 2.54 against 2.34). They are two different estimators of the same parameters. Here the moments are only for starting; the answer is the one from optim. (We used var, which divides by n − 1; with divisor n the starting point would change a little, and optim would still reach the same maximum.)
If in the exam optim gives you a $convergence other than 0, or parameters that look nothing like the data, run it again from the moments. It is two lines and it leaves you close to the maximum.
The complete program: your own interval function
The goal: the confidence interval for the mean goals per match, λ, programmed properly. With large samples, topic 11 gives λ̂ ± z · √(λ̂/n).
Where the formula comes from, with the league’s numbers
λ̂ ± z · √(λ̂/n) looks like it came out of nowhere, but it is five steps from topics 9 and 11, which can be done with our numbers:
| Step | Calculation | Why |
|---|---|---|
| 1 | λ̂ = 173 / 30 = 5.7667 | the estimator of λ is the mean of the goals: 173 goals in 30 matches |
| 2 | Var(X) = λ | in a Poisson, the variance equals the mean |
| 3 | Var(λ̂) = λ / n | the mean of n independent values has the variance of one divided by n |
| 4 | se = √(5.7667 / 30) = √0.1922 = 0.4384 | we do not know λ, so we put λ̂ in its place; the square root turns the variance into a deviation (the standard error) |
| 5 | 5.7667 ± 1.96 · 0.4384 = 5.7667 ± 0.8593 | with large n, λ̂ is almost normal (the CLT), and ±1.96 deviations leave 95 % inside: from 4.91 to 6.63 |
It is exactly what the line in version 1 does: lambda_hat is step 1, sqrt(lambda_hat / n) is step 4 and the 1.96 is step 5. And notice what everything rests on: step 5, which needs large n. When it is not, the formula promises a 95 % it does not deliver, and that is what version 3 measures.
Check you’ve got it: if the league had 120 matches with the same mean, 5.77, how wide would the 95 % interval be?
Half as wide: it would go from 5.34 to 6.20, a width of 0.86 instead of 1.72.
n is inside the square root. With four times as many matches, √(λ̂/n) is divided by √4 = 2. The calculation: √(5.7667 / 120) = 0.2192 and 1.96 · 0.2192 = 0.43, so 5.77 ± 0.43.
That is why precision is so expensive: for an interval half as wide you need four times as much data, not twice as much.
Version 1: by hand
# Version 1: the interval for lambda, written by hand lambda_hat <- mean(goals) n <- length(goals) lambda_hat + c(-1, 1) * 1.96 * sqrt(lambda_hat / n)
Output:
[1] 4.907341 6.625993
Between 4.91 and 6.63 goals per match. Correct, but the 1.96 is typed by hand (if tomorrow they ask for 99 %, you have to remember to change it), the code depends on lambda_hat and n existing with those names, and it checks nothing (data with a −1 or a 2.5 would give a meaningless interval without a word).
Version 2: a function with a level, checks and a list
# Version 2: a function with a level, checks and a list as output
ci_poisson <- function(x, level = 0.95) {
stopifnot(is.numeric(x), all(x >= 0), all(x == round(x)), level > 0, level < 1)
n <- length(x)
est <- mean(x)
z <- qnorm(1 - (1 - level) / 2)
list(estimate = est, ci = est + c(-1, 1) * z * sqrt(est / n), level = level, n = n)
}
r <- ci_poisson(goals)
round(r$ci, 2)
round(ci_poisson(goals, level = 0.99)$ci, 2)
Output:
[1] 4.91 6.63 [1] 4.64 6.90
What has changed:
- The quantile comes from the level:
qnorm(1 - (1 - level) / 2). For 0.95,qnorm(0.975)= 1.96; for 0.99,qnorm(0.995)= 2.576. With 99 % the interval widens (from 4.64 to 6.90): more confidence, less precision. - The checks say what a Poisson is: numbers, non-negative and whole (
x == round(x)). And a level between 0 and 1, so nobody typeslevel = 95. - It returns a list with everything needed to write the answer: the estimate, the interval, the level and the size.
The quantile is the line people get wrong most often in the exam, so let’s go slowly. A 95 % interval leaves 5 % outside, split between the two tails: 2.5 % at the bottom and another 2.5 % at the top. The z we want is the point that leaves below it everything except the upper tail: 1 − 0.025 = 0.975. That is what 1 - (1 - level) / 2 computes:
| Level | Left outside (1 − level) | In each tail | Quantile | z |
|---|---|---|---|---|
| 0.90 | 0.10 | 0.05 | qnorm(0.95) | 1.645 |
| 0.95 | 0.05 | 0.025 | qnorm(0.975) | 1.96 |
| 0.99 | 0.01 | 0.005 | qnorm(0.995) | 2.576 |
It reads from left to right: more confidence, less room in each tail, a bigger z and a wider interval. It is the 4.64-6.90 of 99 % against the 4.91-6.63 of 95 %.
Writing level = 95 instead of level = 0.95. With version 2 nothing serious happens: the check stops it with «Error in ci_poisson(goals, level = 95) : level < 1 is not TRUE». That message is exactly what you want. Without stopifnot, the calculation would be qnorm(1 - (1 - 95) / 2), that is, qnorm(48): a NaN with a warning, and an interval of two NaN that tells you nothing.
Version 3: checking that it delivers (the coverage)
A 95 % interval should contain the true value in 95 % of samples. With real data we do not know it, but by simulating we do: we fix λ, simulate many samples, compute the interval for each one and count how many contain λ.
# Does it deliver 95 %? Simulated coverage with lambda known
coverage <- function(lambda, n, B = 5000) {
inside <- replicate(B, {
ci <- ci_poisson(rpois(n, lambda))$ci
ci[1] <= lambda && lambda <= ci[2]
})
mean(inside)
}
set.seed(2)
coverage(lambda = 6, n = 30)
coverage(lambda = 0.5, n = 10)
Output:
[1] 0.9536 [1] 0.8772
With a league like ours (λ = 6, n = 30), the interval is right 95.36 % of the time: what it promises. But with 10 values of something rare (λ = 0.5, for example the goals of a very weak team), only 87.72 %. That is the story from the beginning.
A new piece of code: replicate(B, { … }). A multi-line chunk of code fits inside braces, and what it returns is the last line: here, whether λ fell inside the interval. && is the single-value “and” (for the TRUE/FALSE of one interval); the single & is the vectorised one.
Why does it fail with a small λ? With λ = 0.5 and 10 values, many samples are almost all zeros. If all of them come out as 0, λ̂ = 0 and the interval is [0, 0]: it cannot contain 0.5. The normal approximation needs n · λ not to be small.
The coverage from the inside, with five samples
coverage(lambda = 0.5, n = 10) does the same thing 5000 times and only shows the final result. With five samples you can look at each one:
# The coverage from the inside: 5 samples of 10 matches with lambda = 0.5 set.seed(8) samples <- replicate(5, rpois(10, 0.5)) # one sample per column colSums(samples) # total goals in each sample cis <- sapply(1:5, function(b) ci_poisson(samples[, b])$ci) round(cis, 2) # row 1: lower end; row 2: upper end cis[1, ] <= 0.5 & 0.5 <= cis[2, ] # does each one contain lambda = 0.5?
Output:
[1] 7 2 6 8 4
[,1] [,2] [,3] [,4] [,5]
[1,] 0.18 -0.08 0.12 0.25 0.01
[2,] 1.22 0.48 1.08 1.35 0.79
[1] TRUE FALSE TRUE TRUE TRUE
Here replicate returns a matrix: each sample is a vector of 10 numbers, so it stores them in columns. And the last line uses & and not &&, because we compare the five intervals at once.
| Sample | Total goals | λ̂ | Interval | Contains 0.5? | Why |
|---|---|---|---|---|---|
| 1 | 7 | 0.7 | from 0.18 to 1.22 | Yes | 0.5 lies between the two ends |
| 2 | 2 | 0.2 | from −0.08 to 0.48 | No | λ̂ is so low that the upper end does not reach 0.5 |
| 3 | 6 | 0.6 | from 0.12 to 1.08 | Yes | centred close to 0.5 |
| 4 | 8 | 0.8 | from 0.25 to 1.35 | Yes | λ̂ overshoots, but the interval still reaches down to 0.25 |
| 5 | 4 | 0.4 | from 0.01 to 0.79 | Yes | λ̂ falls short, but the interval reaches 0.79 |
Four out of five, 80 %. With five samples you cannot conclude anything (that is why the function uses thousands), but you can already see where the problem is: sample 2. It is not all zeros; it has two goals in ten matches, something fairly normal with λ = 0.5. And it has another oddity: the lower end is negative, −0.08, an impossible mean number of goals. The Wald formula does not know that λ cannot be negative.
The note above talks about the extreme case, all zeros, but that only happens 0.67 % of the time. What really sinks the coverage is more frequent. The total goals of 10 matches are a Poisson(5) (the sum of 10 Poisson(0.5)), so you can count exactly when the interval fails:
| Total goals | λ̂ | Wald interval | Contains 0.5? | Probability |
|---|---|---|---|---|
| 0 | 0 | from 0 to 0 | No | 0.0067 |
| 1 | 0.1 | from −0.10 to 0.30 | No | 0.0337 |
| 2 | 0.2 | from −0.08 to 0.48 | No | 0.0842 |
| 3 | 0.3 | from −0.04 to 0.64 | Yes | 0.1404 |
| 4 to 11 | 0.4 to 1.1 | they contain 0.5 | Yes | 0.7295 |
| 12 or more | 1.2 or more | they start at 0.52 or higher | No | 0.0055 |
Adding up the rows that fail: 0.0067 + 0.0337 + 0.0842 + 0.0055 = 0.13. The real coverage is 1 − 0.13 = 0.87, and the simulation gave 0.8772: it adds up. The interval fails mostly at the bottom, with samples of 1 or 2 goals, which are not rare.
Check you’ve got it: with λ = 0.5 and n = 10, why does a sample with 3 goals in total get it right and one with 2 does not?
With 3 goals, λ̂ = 0.3 and the standard error is √(0.3 / 10) = 0.1732. The interval reaches up to 0.3 + 1.96 · 0.1732 = 0.64, which goes past 0.5.
With 2 goals, λ̂ = 0.2 and √(0.2 / 10) = 0.1414. The interval reaches up to 0.2 + 1.96 · 0.1414 = 0.48: it falls two hundredths short.
The detail that explains it: the width also depends on λ̂. With few goals, the center is low and the interval is also narrow, exactly the opposite of what would be needed to catch the 0.5.
Version 4: two methods, with match.arg
R comes with an exact interval for the Poisson, the one from poisson.test. We give our function an argument to choose the method, with match.arg, which is how R’s own functions do it:
# Version 4: two methods, chosen with match.arg
ci_poisson <- function(x, level = 0.95, method = c("wald", "exact")) {
method <- match.arg(method)
stopifnot(is.numeric(x), all(x >= 0), all(x == round(x)), level > 0, level < 1)
n <- length(x)
est <- mean(x)
ci <- if (method == "wald") {
z <- qnorm(1 - (1 - level) / 2)
est + c(-1, 1) * z * sqrt(est / n)
} else {
as.numeric(poisson.test(sum(x), T = n, conf.level = level)$conf.int)
}
list(estimate = est, ci = ci, level = level, n = n, method = method)
}
round(ci_poisson(goals)$ci, 2)
round(ci_poisson(goals, method = "exact")$ci, 2)
Output:
[1] 4.91 6.63 [1] 4.94 6.69
How match.arg works: the default value of method is the vector of allowed options; if you do not give it, match.arg keeps the first one ("wald"); if you give one, it checks that it is on the list. That way the function documents by itself which methods it accepts.
With our 30 matches, the two intervals almost match (from 4.91 to 6.63 and from 4.94 to 6.69): with 173 goals, the normal approximation is good. poisson.test(sum(x), T = n) uses the fact that the sum of n Poissons is another Poisson; $conf.int is its interval, and as.numeric strips an attribute that comes with it (the level) so that it is a clean vector.
The idea that the sum of n Poissons is another Poisson, with our numbers:
| Step | Calculation | Why |
|---|---|---|
| 1 | 173 goals in 30 matches | poisson.test only needs the total, sum(x), and over how many matches it was counted, T = n |
| 2 | 173 comes from a Poisson(30λ) | adding 30 independent Poisson(λ) gives a Poisson with mean 30λ |
| 3 | exact interval for 30λ: from 148.18 to 200.79 | poisson.test computes it with the Poisson itself, without the normal approximation |
| 4 | divided by 30: from 4.94 to 6.69 | if 30λ is between 148.18 and 200.79, λ is between those values divided by 30 |
The argument T = n does step 4 for you: it tells it that the 173 goals were counted over 30 matches, and it returns the interval per match. Since it does not use the normal, it does not need large n. That is why it also holds up with 10 values and λ = 0.5, as you are about to see.
Which one covers better with small data? We measure the coverage of both for several sizes, with λ = 0.5:
coverage <- function(lambda, n, method, B = 5000) {
mean(replicate(B, {
ci <- ci_poisson(rpois(n, lambda), method = method)$ci
ci[1] <= lambda && lambda <= ci[2]
}))
}
set.seed(3)
sizes <- c(5, 10, 20, 40, 80)
tab <- sapply(c("wald", "exact"), function(m) sapply(sizes, coverage, lambda = 0.5, method = m))
rownames(tab) <- paste0("n=", sizes)
round(tab, 3)
Output:
wald exact n=5 0.916 0.985 n=10 0.868 0.980 n=20 0.925 0.976 n=40 0.944 0.955 n=80 0.940 0.959
Two nested sapplys: the outer one goes through the methods and, for each one, the inner one goes through the sizes. The result is a matrix with one column per method and one row per size. And it reads like this: Wald falls short with small samples (0.868 with n = 10) and gets close to 0.95 around n = 40; the exact one never drops below 0.95 (it overshoots: 0.985 with n = 5, because it is conservative by construction).
matplot(sizes, tab, type = "b", pch = 19, lty = 1, log = "x", ylim = c(0.8, 1),
col = c("#FF6B4A", "#5B4BDB"), main = "Real coverage of the 95 % interval (lambda = 0.5)",
xlab = "Sample size", ylab = "Coverage")
abline(h = 0.95, lty = 2)
In the drawing, the violet line (exact) is always above the dashed 95 % line, and the coral one (Wald) below until the sample grows. The programming moral: a function that computes an interval is tested like any other, and the test is the simulated coverage.
| Method | Advantage | Drawback | When |
|---|---|---|---|
Wald (λ̂ ± z√(λ̂/n)) | simple formula, the one in topic 11 | falls short with a small n · λ | large samples |
Exact (poisson.test) | never under-covers | somewhat wider than needed | small samples or small λ |
How to organise the exam script
In the ME1 assessments you hand in one .R file with the code for each exercise, and you can bring your own .R with the functions you have prepared (no problem statements). Everything in this intensive fits there. This is how I would organise it:
# =====================================================================
# ME1 exam script · Sergio Medina · EC2
# Your own functions at the top; one block per exercise below.
# =====================================================================
# ---- 0. Your own functions ------------------------------------------
summary_stats <- function(x, na.rm = TRUE, k = 1.5, digits = 2) {
# (the one from block 1)
}
ci_poisson <- function(x, level = 0.95, method = c("wald", "exact")) {
# (the one from this block)
}
# ---- Exercise 1 -------------------------------------------------------
set.seed(1)
# a) maximum likelihood estimate
# b) 95 % interval
# ---- Exercise 2 -------------------------------------------------------
set.seed(2)
# a) …
The rules behind it, as the drawing shows:
- Functions at the top and only once. If
summary_statsis defined twice, the last one that ran counts (block 1). At the top they load before anything else and the rest of the script uses them. - One block per exercise with
# ---- Title ----. In RStudio, a comment line that ends in four (or more) dashes is a section: it appears in the editor’s outline (bottom left) and can be folded. Ctrl + Shift + R inserts one. - A seed at the start of each exercise that simulates, so that each one can be run on its own and give the same result.
- Comments with the letter of the part (
# a)), not with the problem statement: the exam does not allow you to bring statements, and besides, the marker looks for your part by its letter. - Round at the end, to the exam’s decimals (2 in ME1):
round(x, 2)on what you write on the sheet, never on the intermediate steps.
Writing the exam script like the console: loose lines half tested, variables with the same name in different exercises (x in 1 and another x in 3) and nothing that can be rerun from top to bottom. Before handing it in: Ctrl + Shift + Enter (run everything) and check that it reaches the end without a single error.
To see the full format of an exam, with four exercises and their points, there is the ME1 EC2 mock exam.
Common mistakes (with R’s real message)
A method that does not exist.
ci_poisson(goals, method = "exacts")
Output:
Error in match.arg(method) : 'arg' should be one of “wald”, “exact”
“‘arg’ should be one of “wald”, “exact””: match.arg checks the option and tells you which ones are valid. It is the same error you will see in R functions such as t.test(…, alternative = "bigger").
optimize without maximum = TRUE.
optimize(loglik, interval = c(0.1, 20), x = goals)$minimum
Output:
[1] 19.99993
No error: it returns 19.99993, which is the edge of the interval. optimize looks for the minimum by default, and the log-likelihood has no minimum inside, so it goes as far as you let it. If an estimate comes out stuck to one end of the interval, be suspicious: either maximum = TRUE is missing, or the interval does not contain the maximum.
A function that gives NaN in optim.
optim(c(1, 1), nll_gamma, x = first_goal, method = "L-BFGS-B")
Output:
Error in optim(c(1, 1), nll_gamma, x = first_goal, method = "L-BFGS-B") : L-BFGS-B needs finite values of 'fn' In addition: Warning message: In dgamma(x, shape = par[1], rate = par[2], log = TRUE) : NaNs produced
“L-BFGS-B needs finite values of ‘fn'”, with the warning “NaNs produced” from dgamma: without lower, the algorithm tried a negative shape or rate, the density does not exist there and everything turns into NaN. The fix is the one from before: lower with positive numbers, or the log scale.
The product that ends up as 0.
prod(dpois(rep(goals, 20), 6)) sum(dpois(rep(goals, 20), 6, log = TRUE))
Output:
[1] 0 [1] -1243.883
With 600 values (the 30 matches repeated 20 times), the likelihood as a product is exactly 0: it is a number so small (around e⁻¹²⁴⁴) that it does not fit in a double. The log-likelihood, −1243.88, is computed without any trouble. With a product that is 0 for every λ, optimize returns anything.
The one-tailed quantile.
lambda_hat + c(-1, 1) * qnorm(0.95) * sqrt(lambda_hat / n)
Output:
[1] 5.045511 6.487822
No message, but wrong: qnorm(0.95) = 1.645 is the quantile of a two-tailed 90 % interval. For 95 % you need to leave 0.025 in each tail: qnorm(0.975). That is why our function computes the quantile from the level and does not let you type it by hand.
Try it in the R playground
Copy the script into the R playground on the site and run it.
goals <- c(5, 7, 4, 6, 8, 3, 6, 5, 9, 4, 6, 7, 5, 2, 6,
8, 5, 7, 4, 6, 10, 5, 6, 3, 7, 5, 6, 8, 4, 6)
# ---- Maximum likelihood ----------------------------------------------
loglik <- function(lambda, x) sum(dpois(x, lambda, log = TRUE))
optimize(loglik, interval = c(0.1, 20), x = goals, maximum = TRUE)
# ---- Interval and its coverage ---------------------------------------
ci_wald <- function(x, level = 0.95) {
z <- qnorm(1 - (1 - level) / 2)
mean(x) + c(-1, 1) * z * sqrt(mean(x) / length(x))
}
ci_wald(goals)
set.seed(2)
inside <- replicate(5000, {
ci <- ci_wald(rpois(10, 0.5))
ci[1] <= 0.5 && 0.5 <= ci[2]
})
mean(inside)
What to look at:
- In the playground’s editor (or RStudio’s), the
# ---- … ----lines show up as sections: fold them. - Compare
$maximumwithmean(goals). - Change the 10 in
rpois(10, 0.5)to 80 and run the last four lines again: does the coverage get close to 0.95? - Try
ci_wald(goals, level = 0.99)and compare the width with the 95 % one.
Summary
| Piece | What for | Example from the article |
|---|---|---|
function(par, x) sum(d…(x, par, log = TRUE)) | the log-likelihood as a function | loglik(6, goals) = −62.19 |
optimize(f, interval, maximum = TRUE) | maximum of one parameter | λ̂ = 5.7667 |
optim(start, nll, method = "L-BFGS-B", lower = …) | several parameters (minimises) | gamma: 2.3416 and 0.5906 |
exp(lpar) inside the function | positive parameters without bounds | same result with Nelder-Mead |
qnorm(1 - (1 - level) / 2) | the quantile from the level | 1.96 for 95 % |
match.arg(method) | choose between named options | "wald" or "exact" |
replicate(B, { … }) + mean | the real coverage of an interval | 0.868 with n = 10 |
# ---- Title ---- | sections of the exam script | one block per exercise |
Three ideas to take with you:
- Write the log-likelihood and let R find the maximum; draw it first, to know where to look and to check there is only one maximum.
- An interval is tested by its coverage. Simulate with the parameter known and count how often it is right: if it promises 95 % and gives 87 %, do not use it with that data.
- The exam script is a program, not a console: functions at the top, one block per exercise, one seed per exercise, and it must run from top to bottom.
What next?
In the R intensive 5 exercises you will write your own log-likelihoods, interval functions with their coverage and a complete exam script, with the cheat sheet for the block.
This block ends the R programming intensive. If you want to go over it from the start, begin with block 1: descriptive statistics, where we wrote the first function; and if the exam is what is coming, everything we have programmed here is what you use in the EC2 mock exam.
Did this article help you? Here is how you can support SergioLearns →
Next step: exercisesR intensive 5: estimation and intervals — exercises with my e-scooter’s range, optimize, optim and your own interval function (and the maximum that was on the edge)Mock exam: the whole EC2, with R alongsideME1 EC2 mock examCheat sheet: the block on one page, to reviewCheat sheetScript: the block's functions, ready for your .RFor your script


