R 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)
I wanted a maximum likelihood estimate of how many hard bumps I hit on average on the ride to campus, and optimize gave me 9.99: exactly the edge of the interval I had given it. It was not a strange result, it was a badly asked question: optimize looks for the minimum unless you tell it maximum = TRUE, and the minimum of a log-likelihood is always at the end.
This article is the hands-on part of block 5, the last one, of the R intensive. The theory (optimize and optim, functions that return the interval with its checks, simulated coverage and how to organise the exam script) is in R intensive 5: estimation and intervals. The statistics are taken as known: maximum likelihood in the ME1 point estimation exercises and intervals in the confidence intervals exercises. Here you program what those topics use: R finding the maximum, your function computing the interval and a simulation telling you whether you can trust it.
Table of Contents
How to use this article
- Open the R playground (or RStudio). The data are written into the code itself.
- Level 1, reproduce and read; level 2, write the interval function; level 3, a full problem in the format of the ME1 exam script. This level closes the intensive: the solutions are written as they would go in your
.R, one block per part with its header. - The solutions are folded, with the reason for every decision.
- Finish with the test and with “For your script”, which here includes the template for the exam file.
The data in the exercise. Over 20 charges I logged the kilometres the e-scooter did from 100 % until it switched off, and over 12 rides the hard bumps on the way to campus. The data are made up for programming, with the shape real ones would have.
km <- c(27.1, 17.6, 28.9, 19.6, 21.4, 25.0, 35.7, 35.9, 12.7, 21.5, 28.2, 15.3, 15.2, 12.2, 12.1,
27.5, 32.1, 31.4, 28.3, 34.9) # range per charge (km)
bumps <- c(3, 5, 2, 4, 6, 3, 1, 4, 5, 3, 2, 4) # hard bumps per ride
round(c(mean_km = mean(km), sd_km = sd(km), mean_bumps = mean(bumps)), 2)
Output:
mean_km sd_km mean_bumps
24.13 8.06 3.50
Level 1: reproduce and read maximum likelihood
The bumps per ride are modelled with a Poisson of mean . Reproduce:
logL <- function(lambda) sum(dpois(bumps, lambda, log = TRUE))
optimize(logL, interval = c(0.1, 10), maximum = TRUE)
mean(bumps)
curve(sapply(x, logL), from = 1, to = 8, main = "Log-likelihood of the bumps",
xlab = expression(lambda), ylab = "log L")
- What estimate does
optimizegive and what does it match? - What is
$objective? - Why use
dpois(…, log = TRUE)andsum, and notprod(dpois(…))? - Why
curve(sapply(x, logL), …)and notcurve(logL(x), …)?
logL takes one value of and sums over the 12 rides. curve passes it a vector of 101 values of x at once; if you give it to logL as it is, dpois pairs each with a ride and the sum makes no sense.
Level 2: write your own interval function
Write ci_mean(x, level = 0.95, digits = 2) that computes the t confidence interval for the mean and returns a list with n, mean, margin, ci (a vector named lower and upper) and level. Conditions:
- Remove the
NAs and check that at least 2 data points are left and that the level is between 0 and 1. - Compute with all the decimals and round only when returning.
Apply it to km and check that it matches t.test(km)$conf.int. Then ask it for the 99 % interval and look at its structure with str.
Expected result for the 95 % interval:
$ci lower upper 20.36 27.90
The quantile is : with level = 0.95, qt(0.975, n - 1). In code, qt(1 - (1 - level) / 2, df = n - 1), which works for any level.
Level 3 (challenge): the scooter’s range, in the exam format
Exercise (15 points). The range (km per charge) is modelled with a gamma of shape and rate , with density , . Use km and your ci_mean function from level 2.
- a) (4 points) Write the gamma log-likelihood as a function of
par = c(k, beta)and maximise it withoptim, starting from the method of moments estimates. Give and to 3 decimal places, check that the algorithm has converged and work out the estimated mean . - b) (3 points) With the fitted gamma, estimate , the probability of being stranded before 15 km, and compare it with the proportion of charges in the sample that did not reach 15 km. Draw the histogram of
kmon the density scale with the fitted gamma density on top. - c) (4 points) Compute the 95 % confidence interval for the mean range with
ci_meanand explain what it means in context. - d) (4 points) The t interval assumes normal data, and the range data are not normal. Write a function
covers(B, n, shape, rate, level)that estimates by simulation the actual coverage ofci_meanwith gamma data. Use it withset.seed(28)and B = 2000 for the scooter’s case (, , ) and for a very skewed one with few data (, , ).
optim minimises by default. To maximise, control = list(fnscale = -1). With two parameters that must be positive, method = "L-BFGS-B" and lower = c(0.01, 0.001) stop the algorithm from trying impossible values.
Solutions
Level 1
Before you open the solution, the approach. There is only one parameter, , so the tool is optimize, which searches inside an interval; optim is for two or more, and it arrives in level 3. What gets maximised is not the likelihood but its logarithm. To see what optimize does inside, do it by hand: try a few values of and keep the one with the highest log-likelihood.
lambdas <- c(0.1, 1, 2, 3.5, 5, 10) # a few test values, by hand round(sapply(lambdas, logL), 2) # the log-likelihood at each one prod(dpois(rep(bumps, 50), 3.5)) # the likelihood without the log, with 600 rides
Output:
[1] -130.36 -44.45 -27.34 -21.83 -24.85 -55.74 [1] 0
The log-likelihood rises up to (−21.83, the highest) and falls again. The two edges, 0.1 and 10, are the worst values in the list: that is why, if optimize looks for the minimum, it ends up at an edge. Trying values by hand shows the shape, but it does not give the decimals; optimize does the same thing cleverly, narrowing the interval around the maximum until the difference is smaller than its tolerance.
The last line is the reason for the logarithm: with the 12 rides repeated 50 times, the likelihood at the best already comes out as 0, because the product is so small the computer cannot store it. And if everything is 0, there is no maximum to look for.
See the level 1 solution
logL <- function(lambda) sum(dpois(bumps, lambda, log = TRUE)) optimize(logL, interval = c(0.1, 10), maximum = TRUE) mean(bumps)
Output:
$maximum [1] 3.499999 $objective [1] -21.83392 [1] 3.5
- bumps per ride, which matches the sample mean: for the Poisson, the maximum likelihood estimator is (you proved it in the point estimation topic).
optimizegives 3.499999 because it searches numerically and stops when the difference is below its tolerance: to 2 decimal places, 3.50. - The value of the function at the maximum, the maximum log-likelihood: . It is used to compare models (the one with the higher log-likelihood fits better); on its own it has no interpretation.
- Because of tiny numbers. Each is less than 1, and the product of many of them gets close to 0 so fast that the computer rounds it to 0 (with 400 data, always). The logarithm turns the product into a sum and the maximum is in the same place.
curve(sapply(x, logL), from = 1, to = 8, main = "Log-likelihood of the bumps",
xlab = expression(lambda), ylab = "log L")
- Because
logLis not vectorised. It is meant for one ;sapply(x, logL)calls it with each of the valuescurvewants to draw. In the plot, the curve has a single maximum at 3.5 and falls on both sides; the lowest point of the whole interval given tooptimize(from 0.1 to 10) is at the edge, which is what you get if you forgetmaximum = TRUE.
Check you’ve got it: what would optimize return with interval = c(0.1, 3) and maximum = TRUE?
Almost 3 (2.999955). The real maximum, 3.5, is outside the interval, and inside it the log-likelihood keeps rising up to the right edge: the highest point optimize can find is that edge. That is why it pays to draw the curve first and pick an interval that leaves the maximum well inside. If the answer coincides with one end of the interval, be suspicious.
Level 2
The approach, before the code. The interval is “mean ± quantile times standard error”, , and the function only has to do that in order: clean the data, check that it can be computed, compute and, at the end, round. Each condition in the statement is one of those steps.
Why the t quantile and not the normal’s 1.96, the one you know by heart? Because the standard deviation does not come from the model: it is sd(km), computed from the same 20 data points, and the t pays for that extra uncertainty with wider tails.
n <- length(km); s <- sd(km)
round(c(t = qt(0.975, n - 1), z = qnorm(0.975)), 2) # the two quantiles
round(c(margin_t = qt(0.975, n - 1) * s / sqrt(n),
margin_z = qnorm(0.975) * s / sqrt(n)), 2) # the two margins
Output:
t z
2.09 1.96
margin_t margin_z
3.77 3.53
With 1.96 the margin would be 3.53 km instead of 3.77: a narrower interval that promises a 95 % it does not have. With 20 data points the difference is small; with 5, the t quantile is already 2.78.
See the level 2 solution
# ci_mean(): t interval for the mean, with its checks
ci_mean <- function(x, level = 0.95, digits = 2) {
x <- x[!is.na(x)] # NAs out
stopifnot(is.numeric(x), length(x) >= 2, level > 0, level < 1)
n <- length(x); m <- mean(x); s <- sd(x)
t <- qt(1 - (1 - level) / 2, df = n - 1) # two-tailed quantile
margin <- t * s / sqrt(n)
list(n = n, mean = round(m, digits), margin = round(margin, digits),
ci = round(c(lower = m - margin, upper = m + margin), digits), level = level)
}
r <- ci_mean(km)
r
round(t.test(km)$conf.int, 2)
str(ci_mean(km, 0.99))
Output:
$n [1] 20 $mean [1] 24.13 $margin [1] 3.77 $ci lower upper 20.36 27.90 $level [1] 0.95 [1] 20.36 27.90 attr(,"conf.level") [1] 0.95 List of 5 $ n : int 20 $ mean : num 24.1 $ margin: num 5.16 $ ci : Named num [1:2] 19 29.3 ..- attr(*, "names")= chr [1:2] "lower" "upper" $ level : num 0.99
How to read it: at 95 %, the mean range is between 20.36 and 27.90 km (24.13 ± 3.77), the same as t.test. At 99 %, the margin grows to 5.16 km and the interval goes from 19.0 to 29.3: more confidence, a wider interval. str shows the whole list at a glance: five elements, each with its type, and ci with its names.
Why it is written this way:
- Comparing with
t.test. Your function and R’s have to give the same; if not, yours has a bug. It is the cheapest check there is. - A list with
ciinside.r$cigives you both ends together,r$ci["lower"]one of them, andr$marginwhat the exam sometimes asks for (“with what precision…?”). Returning only the interval would force you to recompute the rest. digitsas an argument. In the report, 2 decimal places; in a coverage simulation (level 3), many, because a rounded interval can leave out by one cent a value that was inside.length(x) >= 2. With a single data point,sdgivesNAandqtwith 0 degrees of freedom does not exist: better to stop with a clear message.
Level 3
Before you open the solution, the map. The four parts build on levels 1 and 2, and in each one there is an obvious path that is not the right one:
| Part | Path | Why not the obvious one |
|---|---|---|
| a) | optim with fnscale = -1, starting from the moments | optimize only moves one parameter and here there are two, and . From c(1, 1) it also gets there (8.455 and 0.350), but with 22 evaluations instead of 9: the moments, and , already leave it close to the maximum |
| b) | pgamma(15, …) with the parameters from a) and mean(km < 15) | One answers with the model and the other with the sample; the part asks you to compare them |
| c) | ci_mean(km)$ci | Rewriting the formula means risking another mistake; the function has already been checked against t.test |
| d) | replicate with ci_mean(…, digits = 10) and compare with shape / rate | You compare with the model’s true mean, not with mean(km); and with 2 decimals, an interval could leave out, through rounding, a value that was inside |
Part d) is the hardest, because it does not ask about the scooter but about the method: how often does it get it right?
See the level 3 solution
a) Maximum likelihood with optim (4 points).
# ==== Exercise 3a: gamma MLE with optim ====
logL_gamma <- function(par, x) sum(dgamma(x, shape = par[1], rate = par[2], log = TRUE))
start <- c(mean(km)^2 / var(km), mean(km) / var(km)) # method of moments
round(start, 3)
fit <- optim(start, logL_gamma, x = km, method = "L-BFGS-B",
lower = c(0.01, 0.001), control = list(fnscale = -1))
round(fit$par, 3)
fit$convergence # 0 = converged
round(fit$par[1] / fit$par[2], 2) # estimated mean
Output:
[1] 8.955 0.371 [1] 8.454 0.350 [1] 0 [1] 24.13
By moments, and ; by maximum likelihood, and . convergence is 0: the algorithm stopped because it found the maximum, not because it ran out of iterations (that would be a 1). The estimated mean, km, matches the sample mean: in the gamma, maximum likelihood keeps the mean.
Details of the code: logL_gamma takes the two parameters in a vector par because optim moves a vector; the data go in with x = km, which optim passes on to the function. And starting from the method of moments estimates (instead of, say, c(1, 1)) puts the algorithm close to the maximum from the beginning.
b) Stranded before 15 km (3 points).
# ==== Exercise 3b: P(X < 15) with the fitted gamma ====
k_hat <- fit$par[1]; b_hat <- fit$par[2]
round(pgamma(15, shape = k_hat, rate = b_hat), 4) # with the model
mean(km < 15) # in the sample
hist(km, breaks = seq(10, 40, by = 5), freq = FALSE, main = "Scooter range",
xlab = "Kilometres per charge", ylab = "Density")
curve(dgamma(x, shape = k_hat, rate = b_hat), add = TRUE, lwd = 2, col = "red")
Output:
[1] 0.1226 [1] 0.15
The model gives : one charge in eight does not reach 15 km. In the sample, 3 out of 20 did not, 15 %. With 20 data, the difference is half a data point; the model has the advantage that it also answers questions the sample cannot (, for example, where there is no data at all). In the plot, the gamma curve follows the shape of the histogram without copying its bars, which is what you ask of a model with 20 data.
c) The interval for the mean range (4 points).
# ==== Exercise 3c: 95 % CI for the mean ==== ci_mean(km)$ci
Output:
lower upper 20.36 27.90
With 95 % confidence, the scooter’s mean range is between 20.36 and 27.90 km per charge. “95 % confidence” means that the method is right in 95 % of the possible samples: not that 95 % of charges give between 20 and 28 km (that would be asking about single charges, not the mean, and the interval would be much wider).
Writing “there is a 95 % probability that the mean is between 20.36 and 27.90”. The true mean is a fixed number: it is either inside or not. The 95 % belongs to the method, and that is exactly what part d measures.
d) The actual coverage of the interval (4 points).
# ==== Exercise 3d: simulated coverage with gamma data ====
covers <- function(B, n, shape, rate, level = 0.95) {
mu <- shape / rate # the true mean
inside <- replicate(B, {
ci <- ci_mean(rgamma(n, shape, rate), level, digits = 10)$ci
ci["lower"] <= mu & mu <= ci["upper"] # does it catch it?
})
mean(inside) # proportion of hits
}
set.seed(28)
covers(2000, 20, 9, 0.4) # the scooter
covers(2000, 5, 0.8, 0.04) # very skewed and with few data
Output:
[1] 0.936 [1] 0.872
With data like the scooter’s (gamma of shape 9, nearly symmetric, and 20 data), the “95 %” interval is right in 93.6 % of samples: a little less than promised, but close. With very skewed data and 5 data points, only in 87.2 %: out of 100 intervals, about 13 miss instead of 5. In the plot, the first bar nearly touches the 95 % line and the second stays clearly below it. The t interval is robust with moderate samples and data that are not very skewed; with few data and strong skew, its 95 % is a promise it does not keep.
How it is marked (indicative, my own, not official). a: 2 points for the log-likelihood and optim with fnscale = -1, 1 for convergence and 1 for the mean. b: 2 for the two probabilities and 1 for the plot. c: 2 for the interval and 2 for interpreting it correctly. d: 2 for the function (with many decimals in ci_mean) and 2 for the two coverages compared with 95 %.
Check you’ve got it: in part d), why does the function compare with shape / rate and not with mean(km)?
Because in a simulation the true mean is known: we set it ourselves when we choose the model. For the scooter, km; for the skewed case, km. Each simulated sample gives its interval, and what gets counted is whether it catches that fixed number. mean(km) is the mean of one particular sample, your 20 charges: it is not what the interval is trying to catch, just one more estimate. Comparing with it, you would not be measuring the coverage of anything.
What’s wrong here?
Snippet 1. The story from the start.
optimize(logL, interval = c(0.1, 10))
Output:
$minimum [1] 9.999945 $objective [1] -55.74097
Without maximum = TRUE, optimize looks for the minimum, and a log-likelihood with a single maximum (the one in the level 1 plot) falls towards both sides: its minimum inside the interval is at one of the edges. A result stuck to the edge of the interval is always a warning sign: either the maximum is outside, or you searched for the opposite of what you wanted.
Using optimize or optim to maximise without telling them. Fix: optimize(…, maximum = TRUE) and, in optim, control = list(fnscale = -1).
Snippet 2. A 95 % interval that comes out too narrow.
m <- mean(km); s <- sd(km); n <- length(km) round(m + c(-1, 1) * qt(0.95, n - 1) * s / sqrt(n), 2)
Output:
[1] 21.01 27.25
It gives 21.01 to 27.25, narrower than the right one (20.36 to 27.90). qt(0.95, …) leaves 5 % in one tail; a two-tailed 95 % interval splits the 5 % in two: 2.5 % on each side, qt(0.975, …). This interval is actually a 90 % one.
Write the quantile in terms of the level, qt(1 - (1 - level) / 2, n - 1), and you will not have to think whether it is 0.95 or 0.975 every time.
round(m + c(-1, 1) * qt(0.975, n - 1) * s / sqrt(n), 2)
Output:
[1] 20.36 27.90
Snippet 3. The exam script, run from scratch. In your session everything worked because you had created dat in the console; whoever marks it opens the .R in a clean session.
rm(list = ls()) # how the marker starts: nothing in memory
# ==== Exercise 2 ====
source_ok <- exists("ci_mean")
source_ok
ci_mean(dat)
Output:
[1] FALSE Error in ci_mean(dat) : could not find function "ci_mean"
R stops at the first failure: the function ci_mean does not exist in a new session, and if it did, the data dat would not exist either. They were in your Environment (from tests in the console or another script), but the .R you hand in does not create them.
Handing in a script that only works in your session. Fix: the .R starts with the functions and data it uses, and before handing it in you run it all with an empty session (in RStudio, Session → Restart R and then Source).
# Functions at the top, then each exercise's data
ci_mean <- function(x, level = 0.95, digits = 2) {
x <- x[!is.na(x)]
stopifnot(is.numeric(x), length(x) >= 2, level > 0, level < 1)
n <- length(x); m <- mean(x); s <- sd(x)
margin <- qt(1 - (1 - level) / 2, df = n - 1) * s / sqrt(n)
list(n = n, mean = round(m, digits), margin = round(margin, digits),
ci = round(c(lower = m - margin, upper = m + margin), digits), level = level)
}
# ==== Exercise 2 ====
dat <- c(27.1, 17.6, 28.9, 19.6, 21.4)
ci_mean(dat)$ci
Output:
lower upper 16.87 28.97
Test: read the code
Ten questions on reading code. They do not count and you can repeat them.
What does this code print (rounded)?
x <- c(2, 4, 3, 3) f <- function(l) sum(dpois(x, l, log = TRUE)) round(optimize(f, c(0.1, 10), maximum = TRUE)$maximum, 2)
[1] 3[1] 10[1] 0.1[1] 12
Solution
Answer: [1] 3
With maximum = TRUE, optimize finds the maximum of the log-likelihood, which for the Poisson is at .
What is wrong with this code?
x <- c(2, 4, 3, 3) f <- function(l) sum(dpois(x, l, log = TRUE)) optimize(f, c(0.1, 10))$minimum
- It looks for the minimum of the log-likelihood, which is on an edge of the interval
- Nothing: it gives the maximum likelihood estimator
- Error:
optimizeneeds a starting vector - Error:
dpoisdoes not acceptlog = TRUE
Solution
Answer: It looks for the minimum of the log-likelihood, which is on an edge of the interval
optimize minimises by default. A log-likelihood with a single maximum falls towards both sides, so its minimum within the interval is an end (here, close to 10).
What number does it print? Write just the number.
level <- 0.90 1 - (1 - level) / 2
Solution
Answer: 0.95
1 − 0.10 / 2 = 0.95: for a two-tailed 90 % interval, the quantile used is 0.95.
What does control = list(fnscale = -1) do in this call?
optim(c(1, 1), logL, x = dat, method = "L-BFGS-B",
lower = c(0.01, 0.01), control = list(fnscale = -1))- It makes
optimmaximise instead of minimise - It makes the function return negative values
- It limits the parameters to negative values
- It reduces the scale so it runs faster
Solution
Answer: It makes optim maximise instead of minimise
optim always minimises. With fnscale = -1 it minimises , which is the same as maximising : what you need with a log-likelihood.
What does it mean when fit$convergence is 0?
- That the algorithm stopped because it found an optimum
- That the maximum log-likelihood is 0
- That it found nothing
- That the estimated parameters are 0
Solution
Answer: That the algorithm stopped because it found an optimum
optim returns a list: $par (estimates), $value (the function at the optimum) and $convergence (0 if all went well). Checking it is part of using optim properly.
What does this code print?
f <- function(x) {
stopifnot(length(x) >= 2)
mean(x)
}
f(7)- Error:
length(x) >= 2 is not TRUE [1] 7[1] NA- A warning and then
[1] 7
Solution
Answer: Error: length(x) >= 2 is not TRUE
stopifnot throws an error as soon as a condition is FALSE, and the message says which one.
What goes wrong when plotting this function?
x0 <- c(2, 4, 3, 3) logL <- function(l) sum(dpois(x0, l, log = TRUE)) curve(logL(x), from = 1, to = 6)
logLsums over all thelvalues at once and does not return one value per point: you needsapply(x, logL)- Nothing: it draws the log-likelihood curve
add = TRUEis missingcurvedoes not accept your own functions
Solution
Answer: logL sums over all the l values at once and does not return one value per point: you need sapply(x, logL)
curve calls the expression with a vector x. logL is meant for a single value and returns one number, not 101: curve fails because the length does not match. curve(sapply(x, logL), …) fixes it.
About a 95 % confidence interval for the mean, (20.36, 27.90) km, mark true or false.
- The method used to compute it is right in 95 % of the possible samples (if its assumptions hold).
- 95 % of the charges give between 20.36 and 27.90 km.
- Computed at 99 %, the interval comes out wider.
- With more data, the 95 % interval comes out wider.
Solution
- T — The method used to compute it is right in 95 % of the possible samples (if its assumptions hold).
- F — 95 % of the charges give between 20.36 and 27.90 km.
- T — Computed at 99 %, the interval comes out wider.
- F — With more data, the 95 % interval comes out wider.
The 95 % belongs to the method, not to single data points. More confidence, wider; more data, narrower (the margin goes with ).
What does this code print?
r <- list(mean = 24.13, ci = c(lower = 20.36, upper = 27.90)) r$ci["upper"] - r$ci["lower"]
upperand below7.54[1] 7.54without a name- Error: you cannot subtract inside a list
[1] 3.77
Solution
Answer: upper and below 7.54
r$ci is a named vector; r$ci["upper"] and r$ci["lower"] are named numbers. Their difference, 27.90 − 20.36 = 7.54, is the width of the interval (twice the margin).
What does this code estimate?
mean(replicate(2000, {
x <- rexp(10, 1)
ci <- t.test(x)$conf.int
ci[1] <= 1 & 1 <= ci[2]
}))- The actual coverage of the 95 % t interval with 10 exponential data of mean 1
- The mean of 2000 exponentials
- The theoretical confidence level, exactly 0.95
- The probability that an exponential is greater than 1
Solution
Answer: The actual coverage of the 95 % t interval with 10 exponential data of mean 1
Each repetition simulates a sample, computes its interval and records whether it contains the true mean (1). The proportion of hits is the actual coverage, which with skewed data and few points falls below 95 %.
Try it in the R playground
Paste this script into the R playground. It simulates 50 intervals and draws them: those that miss the mean, in red.
set.seed(4)
mu <- 24; n <- 15
ints <- t(replicate(50, { x <- rnorm(n, mu, 8); mean(x) + c(-1, 1) * qt(0.975, n - 1) * sd(x) / sqrt(n) }))
miss <- ints[, 1] > mu | ints[, 2] < mu
plot(NULL, xlim = range(ints), ylim = c(1, 50), xlab = "km", ylab = "Sample", main = "50 intervals at 95 %")
segments(ints[, 1], 1:50, ints[, 2], 1:50, col = ifelse(miss, "red", "grey40"), lwd = 2)
abline(v = mu, lty = 2)
sum(miss)
What to look at:
- Almost every segment crosses the dashed line (the true mean); a few, in red, do not.
sum(miss)counts the red ones: out of 50, you expect about 2 or 3 (5 %).- Change
qt(0.975, …)toqt(0.95, …): the segments shrink and more red ones appear. - Change
n <- 15ton <- 60: the segments get shorter, but the proportion of red ones does not change.
Cheat sheet: optimization and intervals in R
The essentials in 30 seconds: the log-likelihood is programmed with sum(d…(x, …, log = TRUE)); one parameter, optimize(f, interval, maximum = TRUE); several, optim(start, f, control = list(fnscale = -1)), and look at $convergence. An interval is a function that checks its input, uses the two-tailed quantile and returns a list. And if you doubt its 95 %, simulate it.
| I want to… | Code | Result |
|---|---|---|
| Log-likelihood | function(p) sum(dpois(x, p, log = TRUE)) | one number per value of p |
| Maximum with one parameter | optimize(f, c(a, b), maximum = TRUE)$maximum | estimate |
| Maximum with several | optim(start, f, x = dat, control = list(fnscale = -1))$par | vector |
| Positive parameters | method = "L-BFGS-B", lower = c(0.01, 0.001) | no impossible values |
| Has it converged? | fit$convergence == 0 | TRUE |
| Plot a non-vectorised function | curve(sapply(x, f), from, to) | curve |
| Two-tailed quantile | qt(1 - (1 - level) / 2, n - 1) | 2.09 with n = 20 at 95 % |
| R’s t interval | t.test(x, conf.level = 0.95)$conf.int | two ends |
| Probability with the fitted model | pgamma(15, k_hat, b_hat) | probability |
| Simulated coverage | mean(replicate(B, lower <= mu & mu <= upper)) | proportion |
Templates from the exercises: bumps, ; range, , , mean 24.13 km, 95 % CI (20.36; 27.90); coverages 0.936 and 0.872.
| Symptom | Likely cause |
|---|---|
optimize gives an end of the interval | maximum = TRUE is missing (or the maximum is outside) |
optim gives huge or near-zero parameters | fnscale = -1 is missing, or the lower limits are |
The interval comes out narrower than t.test‘s | One-tailed quantile: qt(0.95) instead of qt(0.975) |
curve gives an error or a straight line | The function is not vectorised: sapply(x, f) |
| The script fails when marked | It uses objects that only existed in your session |
Before you hand it in, ask yourself:
- Have I written
maximum = TRUEorfnscale = -1and checked convergence? - Does my interval match
t.test‘s? - Have I interpreted the interval as being about the mean, not single data points?
- Have I run the whole
.Rwith an empty session?
For your script
The block’s code, commented and without problem statements, and the template for the file you upload at the end of the ME1 exam. With the five blocks of the intensive you have the functions for the whole course.
# ===================== Block R5: maximum likelihood, intervals and coverage =====================
# mle_1(logL, interval): maximum likelihood estimator with one parameter
mle_1 <- function(logL, interval) {
o <- optimize(logL, interval = interval, maximum = TRUE)
if (min(abs(o$maximum - interval)) < 1e-3 * diff(interval))
warning("The maximum is on the edge: widen the interval")
o$maximum
}
# mle_optim(logL, start, x, lower): estimators with several parameters (logL(par, x))
mle_optim <- function(logL, start, x, lower = rep(1e-3, length(start))) {
a <- optim(start, logL, x = x, method = "L-BFGS-B", lower = lower,
control = list(fnscale = -1))
if (a$convergence != 0) warning("optim has not converged (code ", a$convergence, ")")
a$par
}
# Frequently used log-likelihoods
logL_pois <- function(lambda, x) sum(dpois(x, lambda, log = TRUE))
logL_exp <- function(lambda, x) sum(dexp(x, lambda, log = TRUE))
logL_gamma <- function(par, x) sum(dgamma(x, shape = par[1], rate = par[2], log = TRUE))
# ci_mean(x, level): t interval for the mean, with checks
ci_mean <- function(x, level = 0.95, digits = 2) {
x <- x[!is.na(x)]
stopifnot(is.numeric(x), length(x) >= 2, level > 0, level < 1)
n <- length(x); m <- mean(x); s <- sd(x)
margin <- qt(1 - (1 - level) / 2, df = n - 1) * s / sqrt(n)
list(n = n, mean = round(m, digits), margin = round(margin, digits),
ci = round(c(lower = m - margin, upper = m + margin), digits), level = level)
}
# coverage(generate, mu, B, level): proportion of intervals that catch mu
# 'generate' is a function with no arguments that returns a sample
coverage <- function(generate, mu, B = 2000, level = 0.95) {
mean(replicate(B, {
ci <- ci_mean(generate(), level, digits = 10)$ci
ci["lower"] <= mu & mu <= ci["upper"]
}))
}
# Quick check with the scooter (the data again: snippet 3 emptied the session)
km <- c(27.1, 17.6, 28.9, 19.6, 21.4, 25.0, 35.7, 35.9, 12.7, 21.5, 28.2, 15.3, 15.2, 12.2, 12.1,
27.5, 32.1, 31.4, 28.3, 34.9)
bumps <- c(3, 5, 2, 4, 6, 3, 1, 4, 5, 3, 2, 4)
mle_1(function(l) logL_pois(l, bumps), c(0.1, 10))
round(mle_optim(logL_gamma, c(9, 0.4), km), 3)
set.seed(28)
coverage(function() rgamma(20, 9, 0.4), mu = 9 / 0.4)
Output:
[1] 3.499999 [1] 8.454 0.350 [1] 0.936
And the template for the exam file: one block per exercise, the functions at the top, no problem statements.
# ============================================================
# ME1 · EC<n> · <your name>
# Script for the exercises (runs in full, top to bottom)
# ============================================================
# ---- 0. Packages and functions (paste here the ones from blocks R1 to R5) ----
# library(MASS) # only if the exercise asks for it
# summ <- function(...) { ... }
# ci_mean <- function(...) { ... }
# ---- Exercise 1 ----
# 1a)
# 1b)
# ---- Exercise 2 ----
# 2a)
# ---- Exercise 3 ----
# 3a)
# ---- Bonus ----
Before uploading the .R, Session → Restart R and Source (or Ctrl + Shift + S in RStudio). If it gets to the end without errors, whoever marks it will too.
What next?
This block brings the R programming intensive to a close. If something about optimize, optim or the interval functions is still hard, go back to the theory, R intensive 5: estimation and intervals; and for the pen-and-paper side, the ME1 confidence intervals exercises.
And to put it all to the test in a full exam, with the R playground alongside and your script ready: the ME1 EC2 mock exam.
Did this article help you? Here is how you can support SergioLearns →
Ready for the exam?ME1 EC2 mock exam — The whole exam with the R playground alongside and your script readyBlock theory: optimize, optim, intervals and the exam scriptR intensive 5: estimation and intervalsCheat sheet: the block on one page, to reviewCheat sheetScript: the block's functions, ready for your .RFor your script


