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.

How to use this article

  1. Open the R playground (or RStudio). The data are written into the code itself.
  2. 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.
  3. The solutions are folded, with the reason for every decision.
  4. 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 λ \lambda . 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")
  1. What estimate does optimize give and what does it match?
  2. What is $objective?
  3. Why use dpois(…, log = TRUE) and sum, and not prod(dpois(…))?
  4. Why curve(sapply(x, logL), …) and not curve(logL(x), …)?

logL takes one value of λ \lambda 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 λ \lambda 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 tn−1, 1−α/2 t_{n-1,\,1-\alpha/2} : 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 X X (km per charge) is modelled with a gamma of shape k k and rate β \beta , with density f(x)=βkΓ(k) xk−1e−βx f(x) = \frac{\beta^k}{\Gamma(k)}\,x^{k-1}e^{-\beta x} , x>0 x > 0 . 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 with optim, starting from the method of moments estimates. Give k^ \hat{k} and β^ \hat{\beta} to 3 decimal places, check that the algorithm has converged and work out the estimated mean k^/β^ \hat{k}/\hat{\beta} .
  • b) (3 points) With the fitted gamma, estimate P(X<15) P(X < 15) , 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 km on the density scale with the fitted gamma density on top.
  • c) (4 points) Compute the 95 % confidence interval for the mean range with ci_mean and 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 of ci_mean with gamma data. Use it with set.seed(28) and B = 2000 for the scooter’s case (n=20 n = 20 , k=9 k = 9 , β=0.4 \beta = 0.4 ) and for a very skewed one with few data (n=5 n = 5 , k=0.8 k = 0.8 , β=0.04 \beta = 0.04 ).

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, λ \lambda , 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 λ \lambda 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 λ=3.5 \lambda = 3.5 (−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 λ \lambda 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
  1. λ^=3.5 \hat{\lambda} = 3.5 bumps per ride, which matches the sample mean: for the Poisson, the maximum likelihood estimator is xˉ \bar{x} (you proved it in the point estimation topic). optimize gives 3.499999 because it searches numerically and stops when the difference is below its tolerance: to 2 decimal places, 3.50.
  2. The value of the function at the maximum, the maximum log-likelihood: log⁡L(3.5)=−21.83 \log L(3.5) = -21.83 . It is used to compare models (the one with the higher log-likelihood fits better); on its own it has no interpretation.
  3. Because of tiny numbers. Each P(X=xi) P(X = x_i) 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")
Log-likelihood of the bumpsOutput of curve: the Poisson log-likelihood for lambda between 1 and 8. It rises from −44.45 at lambda 1 to a maximum of −21.83 at lambda 3.5 and falls to −36 at lambda 8.-45-40-35-30-25-20log L12345678maximum: λ = 3.5, log L = −21.83and keeps falling up to 10:that is where the "minimum" isλ
Redrawn in the site colours: a single maximum, at the mean number of bumps; the edges are the lowest points.
  1. Because logL is not vectorised. It is meant for one λ \lambda ; sapply(x, logL) calls it with each of the values curve wants 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 to optimize (from 0.1 to 10) is at the edge, which is what you get if you forget maximum = 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”, xˉ±tn−1, 1−α/2 s/n \bar{x} \pm t_{n-1,\,1-\alpha/2}\, s/\sqrt{n} , 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 ci inside. r$ci gives you both ends together, r$ci["lower"] one of them, and r$margin what the exam sometimes asks for (“with what precision…?”). Returning only the interval would force you to recompute the rest.
  • digits as 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, sd gives NA and qt with 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:

PartPathWhy not the obvious one
a)optim with fnscale = -1, starting from the momentsoptimize only moves one parameter and here there are two, k k and β \beta . From c(1, 1) it also gets there (8.455 and 0.350), but with 22 evaluations instead of 9: the moments, k=xˉ2/s2 k = \bar{x}^2/s^2 and β=xˉ/s2 \beta = \bar{x}/s^2 , 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)$ciRewriting 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 / rateYou 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, k=8.955 k = 8.955 and β=0.371 \beta = 0.371 ; by maximum likelihood, k^=8.454 \hat{k} = 8.454 and β^=0.350 \hat{\beta} = 0.350 . 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, 8.454/0.350=24.13 8.454 / 0.350 = 24.13 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
Histogram of the range with the fitted gammaDensity histogram of the 20 charges with breaks every 5 km from 10 to 40 (densities 0.03, 0.04, 0.03, 0.05, 0.03 and 0.02) and the fitted gamma density on top, peaking near 21 km. A vertical line marks 15 km.00.010.020.030.040.050.06Density51015202530354045dgamma(k = 8.454; β = 0.350)P(X < 15) = 0.1226Kilometres per charge
Redrawn in the site colours: the curve follows the shape of the bars without copying them.

The model gives P(X<15)=0.1226 P(X < 15) = 0.1226 : 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 (P(X<8) P(X < 8) , 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
Actual coverage of the 95 % t interval with gamma dataTwo bars: with 20 gamma data of shape 9 the interval is right in 93.6 % of 2000 samples; with 5 very skewed data, in 87.2 %. A dashed line marks the promised 95 %.0.80.850.90.951Actual coverage0.936scooter: n = 20, k = 90.872skewed: n = 5, k = 0.8promised: 0.95
The axis starts at 0.80 so the difference shows: with few data and strong skew, the 95 % is not met.

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, k/β=9/0.4=22.5 k/\beta = 9/0.4 = 22.5 km; for the skewed case, 0.8/0.04=20 0.8/0.04 = 20 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.

Question 1Single choice

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. [1] 3
  2. [1] 10
  3. [1] 0.1
  4. [1] 12
Solution

Answer: [1] 3

With maximum = TRUE, optimize finds the maximum of the log-likelihood, which for the Poisson is at xˉ=3 \bar{x} = 3 .

Question 2Single choice

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
  1. It looks for the minimum of the log-likelihood, which is on an edge of the interval
  2. Nothing: it gives the maximum likelihood estimator
  3. Error: optimize needs a starting vector
  4. Error: dpois does not accept log = 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).

Question 3Short answer

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.

Question 4Single choice

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))
  1. It makes optim maximise instead of minimise
  2. It makes the function return negative values
  3. It limits the parameters to negative values
  4. 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 −f -f , which is the same as maximising f f : what you need with a log-likelihood.

Question 5Single choice

What does it mean when fit$convergence is 0?

  1. That the algorithm stopped because it found an optimum
  2. That the maximum log-likelihood is 0
  3. That it found nothing
  4. 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.

Question 6Single choice

What does this code print?

f <- function(x) {
  stopifnot(length(x) >= 2)
  mean(x)
}
f(7)
  1. Error: length(x) >= 2 is not TRUE
  2. [1] 7
  3. [1] NA
  4. 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.

Question 7Single choice

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)
  1. logL sums over all the l values at once and does not return one value per point: you need sapply(x, logL)
  2. Nothing: it draws the log-likelihood curve
  3. add = TRUE is missing
  4. curve does 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.

Question 8True or false

About a 95 % confidence interval for the mean, (20.36, 27.90) km, mark true or false.

  1. The method used to compute it is right in 95 % of the possible samples (if its assumptions hold).
  2. 95 % of the charges give between 20.36 and 27.90 km.
  3. Computed at 99 %, the interval comes out wider.
  4. 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 1/n 1/\sqrt{n} ).

Question 9Single choice

What does this code print?

r <- list(mean = 24.13, ci = c(lower = 20.36, upper = 27.90))
r$ci["upper"] - r$ci["lower"]
  1. upper and below 7.54
  2. [1] 7.54 without a name
  3. Error: you cannot subtract inside a list
  4. [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).

Question 10Single choice

What does this code estimate?

mean(replicate(2000, {
  x <- rexp(10, 1)
  ci <- t.test(x)$conf.int
  ci[1] <= 1 & 1 <= ci[2]
}))
  1. The actual coverage of the 95 % t interval with 10 exponential data of mean 1
  2. The mean of 2000 exponentials
  3. The theoretical confidence level, exactly 0.95
  4. 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:

  1. Almost every segment crosses the dashed line (the true mean); a few, in red, do not.
  2. sum(miss) counts the red ones: out of 50, you expect about 2 or 3 (5 %).
  3. Change qt(0.975, …) to qt(0.95, …): the segments shrink and more red ones appear.
  4. Change n <- 15 to n <- 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…CodeResult
Log-likelihoodfunction(p) sum(dpois(x, p, log = TRUE))one number per value of p
Maximum with one parameteroptimize(f, c(a, b), maximum = TRUE)$maximumestimate
Maximum with severaloptim(start, f, x = dat, control = list(fnscale = -1))$parvector
Positive parametersmethod = "L-BFGS-B", lower = c(0.01, 0.001)no impossible values
Has it converged?fit$convergence == 0TRUE
Plot a non-vectorised functioncurve(sapply(x, f), from, to)curve
Two-tailed quantileqt(1 - (1 - level) / 2, n - 1)2.09 with n = 20 at 95 %
R’s t intervalt.test(x, conf.level = 0.95)$conf.inttwo ends
Probability with the fitted modelpgamma(15, k_hat, b_hat)probability
Simulated coveragemean(replicate(B, lower <= mu & mu <= upper))proportion

Templates from the exercises: bumps, λ^=3.50 \hat{\lambda} = 3.50 ; range, k^=8.454 \hat{k} = 8.454 , β^=0.350 \hat{\beta} = 0.350 , mean 24.13 km, 95 % CI (20.36; 27.90); coverages 0.936 and 0.872.

SymptomLikely cause
optimize gives an end of the intervalmaximum = TRUE is missing (or the maximum is outside)
optim gives huge or near-zero parametersfnscale = -1 is missing, or the lower limits are
The interval comes out narrower than t.test‘sOne-tailed quantile: qt(0.95) instead of qt(0.975)
curve gives an error or a straight lineThe function is not vectorised: sapply(x, f)
The script fails when markedIt uses objects that only existed in your session

Before you hand it in, ask yourself:

  1. Have I written maximum = TRUE or fnscale = -1 and checked convergence?
  2. Does my interval match t.test‘s?
  3. Have I interpreted the interval as being about the mean, not single data points?
  4. Have I run the whole .R with an empty session?
ME1 exam coming up?The script for every topic, the printable cheat sheet and the pack for each exam, for free.See the pack

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