Confidence intervals — exam-style exercises with bananas, irrigation and breakdowns (and the exact pivot that comes up in EC2)
In the EC2 class mock exam I computed the exact exponential interval with qchisq(c(0.05, 0.95), 12) and 12 data points, when the degrees of freedom were 24. Everything before it was right: the gamma of the sum, the density of , the chi-squared. In the last step, in a hurry, I wrote n where I had proved it was 2n, and the interval came out almost twice as wide. I lost the whole part over a number I had written myself three lines higher up. Since then, before moving to R, I copy the degrees of freedom from my own derivation.
These are the exercises for the confidence intervals theory. There are three chained exercises like those in EC2, each with its context and points, and a bonus, all at the banana cooperative: the size of the fruit, two irrigation systems and the breakdowns of the packing-house conveyor belt. They mix paper (derive and solve) and R (compute to two decimals). The solutions come afterwards, with a suggested split of the points, and at the end you have the cheat sheet and the code for your script.
Table of Contents
How to use this article
- Do them with the exam in mind. In ME1’s EC2 you have 4 hours for 50 points, with RStudio and the data open. These three exercises add up to 40 points plus a 2.5-point bonus: give them about 3 hours.
- Paper for what is derived, R for what is computed. Pivots and solving, on paper; the intervals with the data, in R, to 2 decimals as the exam asks. Keep the code in a script: at the end you have to upload the
.Rfile with the code for each exercise. - Read the confidence level of each part. It changes from one to another (90 %, 95 %, 99 %), and the quantiles with it.
- Mark yourself with the criteria. Each solution comes with “How it is marked” and a split of the points. It is a guide, mine: it is not the official marking scheme.
- Finish with the cheat sheet and “For your script”. The cheat sheet has results only (that is what you are allowed to bring, handwritten: two sheets, both sides, in EC2) and “For your script” is the topic’s code, ready for your
.Rfile. If a derivation gets stuck, the confidence interval proofs have it step by step, and the practice, the simulations.
Exercise 1: banana size (10 points)
A farm in La Aldea de San Nicolás grades its fruit by banana length, the size class, in centimetres. From years of measurements, size is known to follow a normal with standard deviation σ = 1.8 cm. These are the sizes of 16 bananas from the last batch:
caliber <- c(20.0, 20.7, 20.7, 20.4, 19.2, 23.4, 21.0, 20.4, 18.5, 22.1,
23.0, 18.9, 19.8, 19.5, 21.5, 22.3)
- (2 points) Build a 90 % confidence interval for the mean size μ, with σ = 1.8 known. Give the margin of error.
- (3 points) Now suppose σ is unknown. Build the 95 % interval for μ, first with the formula and then with
t.test, and explain why it is wider than if you used z. - (3 points) Build 95 % intervals for the variance and for σ. Is the value σ = 1.8 that was taken as known consistent?
- (2 points) How many bananas must be measured to estimate the mean size with an error of at most 0.5 cm and 95 % confidence, with σ = 1.8?
Exercise 2: drip against sprinkler (15 points)
The cooperative wants to know whether drip irrigation yields more fruit than sprinklers. Yield per plant (kg) is weighed on 14 drip-irrigated plants and 13 sprinkler ones, from different plots, and both yields are assumed normal:
drip <- c(47.6, 36.6, 42.0, 43.3, 32.0, 48.2, 42.5, 42.8, 36.0, 39.7, 40.3, 36.8, 42.4, 28.7) sprinkler <- c(24.9, 42.8, 40.2, 41.3, 31.4, 40.4, 33.6, 33.7, 30.8, 37.0, 46.6, 36.4, 30.7)
- (3 points) Build a 90 % interval for the ratio of variances (1 = drip). Can they be assumed equal?
- (4 points) Starting from , derive step by step the expression of the interval in part 1.
- (3 points) With equal variances, build by hand the 95 % interval for (give and the quantile) and check it with
t.test. - (2 points) Compute the Welch interval and compare it with the previous one. Do the data let you claim, with 95 % confidence, that drip yields more?
- (3 points) To repeat the study with the same number of plants in each system, how many are needed per group for the margin of error of at 95 % not to exceed 2 kg? Use the normal approximation and as a pilot value for σ.
Exercise 3: conveyor belt breakdowns (15 points)
The packing-house conveyor belt breaks down every now and then. The time between two breakdowns, X, in hours, is modelled as an exponential(λ), with , . Let be an s.r.s. and . These are the last 12 times between breakdowns:
belt <- c(25.3, 17.3, 39.9, 0.9, 1.7, 9.5, 9.4, 4.4, 81.8, 0.9, 30.1, 14.4)
- (3 points) Using the moment generating function, prove that .
- (3 points) Find the density of and identify its distribution.
- (3 points) Using U as a pivot, build the confidence interval for λ and, from it, for the mean time between breakdowns, .
- (2 points) Build the asymptotic interval for λ, given that the Fisher information of one observation is .
- (4 points) With the data, compute both 90 % intervals for λ and for . Which one do you trust more here, and why?
Bonus (2.5 points)
Two shifts work at the packing house. In the morning 18 out of 150 bunches were rejected and in the afternoon 29 out of 160. Build the 99 % asymptotic interval for the difference in rejection proportions (1 = morning), check the conditions and compare it with prop.test. Does one shift reject more than the other?
Solutions
Exercise 1
1. With known σ, the pivot is and the interval, . At 90 %, and the quantile is .
Why z and not t. The statement says σ = 1.8 is known “from years of measurements”: it is known, and the pivot with σ is exactly normal. Using t would throw that information away and pay for a larger quantile. And the quantile is , not , because the 10 % left out is split between two tails.
n <- length(caliber); alpha <- 0.10 margin <- qnorm(1 - alpha / 2) * 1.8 / sqrt(n) round(c(mean = mean(caliber), z = qnorm(1 - alpha / 2), margin = margin), 3) round(mean(caliber) + c(-1, 1) * margin, 2)
Output:
mean z margin 20.712 1.645 0.740 [1] 19.97 21.45
The margin is cm and the interval, (19.97, 21.45) cm: with 90 % confidence, the batch’s mean size is between 19.97 and 21.45 cm.
2. With unknown σ, and the interval is .
s <- sd(caliber) round(c(s = s, t = qt(0.975, n - 1)), 3) round(mean(caliber) + c(-1, 1) * qt(0.975, n - 1) * s / sqrt(n), 2) round(t.test(caliber, conf.level = 0.95)$conf.int, 2)
Output:
s t 1.439 2.131 [1] 19.95 21.48 [1] 19.95 21.48 attr(,"conf.level") [1] 0.95
(19.95, 21.48) cm, the same with the formula and with t.test. It is wider than if we used with the same s, because the t(15) quantile is 2.131: estimating σ with S adds uncertainty, and the t, with heavier tails, accounts for it. If you used z with s, the interval would promise 95 % and hit less (we measured it in the practice).
Check you’ve got it: what interval would you get at 95 % with z and the sample s, and why is it not valid?
, that is, (20.01, 21.42): 1.41 cm wide against the 1.53 of the t. It looks better for being narrower, but that narrowness is fake: it treats s as if it were the true σ, when it also came from the sample.
3. The pivot is and the interval, , with the big quantile at the bottom.
The setup before the arithmetic. The pivot has in the denominator and we want it alone in the middle. Solving for it flips the fraction, and with it the order: the big quantile, 27.488, gives the small end. That is why the code asks for the quantiles already reversed, qchisq(c(0.975, 0.025), n - 1). For σ you do not need another pivot: the square root is increasing, so you just take the root of both ends.
q <- qchisq(c(0.975, 0.025), n - 1) round(c(s2 = var(caliber), q_big = q[1], q_small = q[2]), 3) round((n - 1) * var(caliber) / q, 2) # sigma^2 round(sqrt((n - 1) * var(caliber) / q), 2) # sigma
Output:
s2 q_big q_small 2.072 27.488 6.262 [1] 1.13 4.96 [1] 1.06 2.23
For , (1.13, 4.96) cm², and for σ, (1.06, 2.23) cm. The value σ = 1.8 is inside the interval for σ, so the data are consistent with it (even though this batch’s s, 1.44, comes out lower).
4. By the sample size formula, :
(qnorm(0.975) * 1.8 / 0.5)^2 ceiling((qnorm(0.975) * 1.8 / 0.5)^2)
Output:
[1] 49.78531 [1] 50
, so you need 50 bananas (always round up).
Why σ = 1.8 and not s. With s = 1.44 you would get about 32 bananas, but that s comes from a single batch of 16; if the next one spreads out as the years of measurements say, the error would go above 0.5 cm. And you round up because n is a minimum: with 49, the margin would be cm.
Check you’ve got it: with an error of 0.25 cm, half as much, how many bananas would you need?
, so 200: about four times as many. The error is divided by , and to halve it you have to multiply n by .
How it is marked (a guide, not official): 1) quantile well chosen 1, interval and margin 1. 2) formula with t and 15 degrees 1, interval 1, explanation of the width 1. 3) quantiles in place 1, interval for 1, the one for σ and the consistency 1. 4) formula 1, 50 rounding up 1.
Exercise 2
1. With R, at 90 %:
m <- length(drip); n <- length(sprinkler)
round(c(m = m, n = n, s2_drip = var(drip), s2_sprinkler = var(sprinkler),
ratio = var(drip) / var(sprinkler)), 3)
round(qf(c(0.95, 0.05), m - 1, n - 1), 3)
round(var.test(drip, sprinkler, conf.level = 0.90)$conf.int, 2)
Output:
m n s2_drip s2_sprinkler ratio
14.000 13.000 29.948 36.263 0.826
[1] 2.660 0.384
[1] 0.31 2.15
attr(,"conf.level")
[1] 0.9
The ratio of the sample variances is 29.948/36.263 = 0.826 and the interval, (0.31, 2.15). It contains 1: with 90 % confidence the variances can be assumed equal.
Why you start with the variances. This part decides the rest: if 1 falls inside, in part 3 you pool the two variances into ; if not, it is Welch. And you look at 1, not 0, because it is a ratio: equal variances means .
Where we want to get to. In the pivot, the ratio is upside down, , and multiplied by . Two moves are needed: divide to remove and take reciprocals so that is left. Inverting the whole F first also works, but and you would change quantiles; this way you use those of that R gives in part 1.
2. With the quantiles of , as F is a pivot:
Dividing all three sides by (the direction does not change):
All three are positive; taking reciprocals reverses the inequalities:
Check with the numbers from part 1: 0.826/2.660 = 0.31 and 0.826/0.384 = 2.15.
3. With and t(25):
sp2 <- ((m - 1) * var(drip) + (n - 1) * var(sprinkler)) / (m + n - 2) round(c(diff = mean(drip) - mean(sprinkler), sp2 = sp2, sp = sqrt(sp2), t = qt(0.975, m + n - 2)), 3) round((mean(drip) - mean(sprinkler)) + c(-1, 1) * qt(0.975, m + n - 2) * sqrt(sp2 * (1 / m + 1 / n)), 2) round(t.test(drip, sprinkler, var.equal = TRUE)$conf.int, 2)
Output:
diff sp2 sp t 3.783 32.979 5.743 2.060 [1] -0.77 8.34 [1] -0.77 8.34 attr(,"conf.level") [1] 0.95
kg and the quantile is 2.060. The margin is , and the interval, (−0.77, 8.34) kg, the same with t.test.
Why weights by 13 and 12. Each variance weighs according to its degrees of freedom. The simple average, 33.106, is close to 32.979 because the sample sizes are almost equal; with 5 plants in one group and 40 in the other, it would not be. And the t has 14 + 13 − 2 = 25 degrees because two are spent estimating the two means.
4.
round(t.test(drip, sprinkler)$conf.int, 2) round(t.test(drip, sprinkler)$parameter, 2)
Output:
[1] -0.80 8.36 attr(,"conf.level") [1] 0.95 df 24.28
Welch gives (−0.80, 8.36), almost the same (with 24.28 degrees of freedom instead of 25): as the variances are similar, either method will do. Both intervals contain 0: although in the sample drip irrigation yields 3.78 kg more per plant, with 95 % confidence the data do not let us claim that it yields more. More plants are needed.
Why you look at 0 and not at the 3.78 kg. The question is about , not about these 27 plants. To claim that drip irrigation yields more, the whole interval would have to be above 0. “We cannot claim it” is not “they are equal”: it is that the margin, 4.55 kg, is larger than the difference.
Before part 5: the 2 and the z. The variance of is : that is where the 2 comes from. And z is used because the degrees of freedom of the t depend on n, which is what you are looking for: the calculation would be circular.
5. With equal sample sizes n and the normal approximation, the margin is . Requiring it not to exceed δ = 2:
2 * (qnorm(0.975) * sqrt(sp2) / 2)^2 ceiling(2 * (qnorm(0.975) * sqrt(sp2) / 2)^2)
Output:
[1] 63.34368 [1] 64
: 64 plants per group, about 128 in total.
How it is marked (a guide, not official): 1) interval 2, conclusion 1. 2) setting up with the pivot 1, division 1, reciprocals with the change of direction 2. 3) and quantile 1, interval 1, check 1. 4) Welch 1, conclusion with the 0 1. 5) margin with equal n 1, solving 1, 64 rounding up 1.
Exercise 3
1. The mgf of the exponential is , for . As the are independent, the mgf of the sum is the product:
which is the mgf of a gamma. By uniqueness of the mgf, .
2. With and , the inverse is with derivative :
It is gamma, that is, a . It does not depend on λ.
Why exactly . Multiplying by λ removes it from the distribution: no longer depends on anything unknown, which is what a pivot needs. The 2 is there to land on a , with quantiles in qchisq and in the tables. That is why the degrees are 2n and not n.
3. U depends on the sample and on λ, and its distribution does not depend on λ: it is a pivot. With the quantiles of :
For , taking reciprocals (the direction reverses): .
4. The MLE is . With , its asymptotic variance is , and replacing λ with :
Before part 5: copy the degrees from your derivation. With 12 breakdowns there are degrees, and at 90 %, the quantiles 0.05 and 0.95. Before writing the qchisq, copy the degrees from part 2: it is the mistake from the story at the start.
Check you’ve got it: what interval for λ would you get with 12 degrees, and how would you notice the mistake?
The quantiles would be 5.226 and 21.026, and with , the interval (0.0111, 0.0446). It does not even contain : an interval that leaves out its own estimate is a warning sign. With the 24 degrees, (0.0294, 0.0773), it does contain it.
5. At 90 %, with n = 12 the quantiles come from :
n <- length(belt); T <- sum(belt); lambda <- n / T round(c(T = T, mean = mean(belt), lambda = lambda), 4) q <- qchisq(c(0.05, 0.95), 2 * n) # 2n = 24 degrees round(q, 3) round(q / (2 * T), 4) # exact, lambda round(2 * T / rev(q), 2) # exact, 1/lambda asym <- lambda + c(-1, 1) * qnorm(0.95) * lambda / sqrt(n) round(asym, 4) # asymptotic, lambda round(1 / rev(asym), 2) # asymptotic, 1/lambda
Output:
T mean lambda 235.6000 19.6333 0.0509 [1] 13.848 36.415 [1] 0.0294 0.0773 [1] 12.94 34.03 [1] 0.0267 0.0751 [1] 13.31 37.38
| 90 % interval | λ (breakdowns per hour) | 1/λ (hours) |
|---|---|---|
| Exact | (0.0294, 0.0773) | (12.94, 34.03) |
| Asymptotic | (0.0267, 0.0751) | (13.31, 37.38) |
With 12 data points I trust the exact one more: its confidence is what it claims for any n, because U has exactly a distribution. The asymptotic one relies on being nearly normal, and with 12 values is still skewed; the drawing shows the exact one shifted to the right of the asymptotic one, which is symmetric around . For the mean, between 12.94 and 34.03 hours between breakdowns with 90 % confidence.
How it is marked (a guide, not official): 1) mgf of the exponential 1, product by independence 1, identification and uniqueness 1. 2) change of variable with the Jacobian 2, identifying 1. 3) pivot and solving for λ 2, interval for 1/λ 1. 4) asymptotic variance 1, interval 1. 5) exact with 24 degrees 1.5, asymptotic 1, intervals for the mean 0.5, reasoned choice 1.
Bonus
p1 <- 18 / 150; p2 <- 29 / 160 round(c(p1 = p1, p2 = p2, diff = p1 - p2), 4) c(150 * p1, 150 * (1 - p1), 160 * p2, 160 * (1 - p2)) # conditions: all >= 5 round((p1 - p2) + c(-1, 1) * qnorm(0.995) * sqrt(p1 * (1 - p1) / 150 + p2 * (1 - p2) / 160), 3) round(prop.test(c(18, 29), c(150, 160), conf.level = 0.99)$conf.int, 3)
Output:
p1 p2 diff 0.1200 0.1812 -0.0612 [1] 18 132 29 131 [1] -0.165 0.043 [1] -0.172 0.049 attr(,"conf.level") [1] 0.99
, and the four quantities (18, 132, 29, 131) are above 5. The 99 % interval is (−0.165, 0.043), and with prop.test, (−0.172, 0.049), slightly wider because of the correction. Both contain 0: with 99 % confidence we cannot say that one shift rejects more than the other.
How it is marked (a guide, not official): proportions and conditions 0.5, quantile 0.5, interval 1, prop.test and conclusion 0.5.
What’s wrong here?
Three pieces of code from classmates with the size data from exercise 1. Before reading the explanation, predict what comes out and what is wrong.
Fragment 1. The 95 % interval for the variance:
q <- qchisq(c(0.025, 0.975), 15) round(15 * var(caliber) / q, 2)
Output:
[1] 4.96 1.13
It gives (4.96, 1.13): the lower limit is bigger than the upper one. The quantiles are in the “natural” order (small, big), but dividing by them, the small one gives the big end. You have to put qchisq(0.975, 15) first.
Not swapping the quantiles when taking reciprocals. If L > U, the “interval” is empty.
Fragment 2. The 95 % interval for the mean with unknown σ:
round(mean(caliber) + c(-1, 1) * qt(0.95, 15) * sd(caliber) / sqrt(16), 2)
Output:
[1] 20.08 21.34
It gives (20.08, 21.34), narrower than the right one (19.95, 21.48). qt(0.95, 15) leaves 5 % in a single tail: it is the quantile of a 90 % interval. For 95 %, qt(0.975, 15).
Fragment 3. The size for an error of 0.45 cm at 95 %:
round((qnorm(0.975) * 1.8 / 0.45)^2)
Output:
[1] 61
It gives 61, but : with 61 bananas the margin is . Round with ceiling: 62.
Three ten-second checks before handing in an interval: that L < U, that the quantile is the one (0.975 for 95 %) and, for a sample size, that the number is a whole number rounded up.
Practice quiz
Before moving on to the next topic, check you have got it. This quiz is here to consolidate what this article explains: the ME1 exam is not a multiple-choice test (you solve problems by hand and with R), so no mark here counts. There are 10 questions on confidence intervals: key ideas, typical mistakes and many «what does this R code print?», with the outputs from really running it. In the short answers, a decimal point or a decimal comma both work. Answer without running anything, press Check and read the explanation for each option; you can repeat it as many times as you like.
For the variance interval with 16 values, a classmate writes 15 * var(calibre) / qchisq(c(0.025, 0.975), 15) and gets (4.96; 1.13). What is wrong?
- When dividing by the quantiles, the small one gives the large end:
qchisq(0.975, 15)must go first - The degrees of freedom are 16
- It should multiply by the quantiles
- It should use the t
Solution
Answer: When dividing by the quantiles, the small one gives the large end: qchisq(0.975, 15) must go first
With the quantiles swapped you get (1.13; 4.96). Ten-second check: L < U.
95 % interval for the mean with σ unknown and n = 16. Which quantile goes in?
qt(0.975, 15)qt(0.95, 15)qnorm(0.975)qt(0.975, 16)
Solution
Answer: qt(0.975, 15)
An interval is estimate ± quantile × standard error, and the quantile is the 1 − α/2 one.
σ = 1.8 cm, maximum error 0.45 cm at 95 %. How many bananas are needed? (ceiling rounds up.)
ceiling((qnorm(0.975) * 1.8 / 0.45)^2)
Solution
Answer: 62
(1.96 · 1.8 / 0.45)² = 61.46. With 61 the margin would be 0.452 > 0.45, so you round up: 62.
What does it print? (95 % interval for the mean with known σ = 2, n = 25 and mean 10.)
round(10 + c(-1, 1) * qnorm(0.975) * 2 / sqrt(25), 2)
Solution
Answer: 9.22 10.78
Standard error 2/5 = 0.4; margin 1.96 · 0.4 = 0.784. The interval is (9.22; 10.78).
Match each parameter (normal population) with its interval’s pivot:
| Mean with σ known | |
| Mean with σ unknown | |
| Variance | |
| Ratio of two variances |
Definitions:
- t(n − 1): (mean − μ)/(S/√n)
- Binomial(n, p)
- F(m − 1, n − 1)
- χ²(n − 1): (n − 1)S²/σ²
- Normal: (mean − μ)/(σ/√n)
Solution
- Mean with σ known → Normal: (mean − μ)/(σ/√n)
- Mean with σ unknown → t(n − 1): (mean − μ)/(S/√n)
- Variance → χ²(n − 1): (n − 1)S²/σ²
- Ratio of two variances → F(m − 1, n − 1)
With large n and any model, the MLE ± z times its standard error gives an asymptotic interval.
The 95 % interval for the difference of irrigation means is (−0.77; 8.34). What can you say?
- It contains 0: with these data you cannot claim the means are different
- The means are different, because the interval is wide
- The first mean is certainly larger
- The interval is wrong because one end is negative
Solution
Answer: It contains 0: with these data you cannot claim the means are different
For a ratio of variances, the same with 1: if the interval contains 1, the variances could be equal.
True or false?
- For a 90 % interval, the quantile is the 0.95 one.
- Once computed from the data, a 95 % interval contains the parameter with probability 0.95.
- With two paired samples you work with the differences.
- If many samples are simulated, about 95 % of the 95 % intervals contain the parameter.
Solution
- T — For a 90 % interval, the quantile is the 0.95 one.
- F — Once computed from the data, a 95 % interval contains the parameter with probability 0.95.
- T — With two paired samples you work with the differences.
- T — If many samples are simulated, about 95 % of the 95 % intervals contain the parameter.
Once computed, the interval either contains the parameter or not: the 95 % is the proportion of intervals that get it right in the long run (the coverage the article’s simulation measures, 0.96).
What does it print? (3 decimals.)
round(qt(0.975, 15), 3)
Solution
Answer: 2.131
With 15 degrees of freedom, the t leaves 2.5 % above 2.131: it is the quantile for the 95 % interval of the mean with 16 values and σ unknown.
Put in order the checks before handing in an interval:
- Choose the pivot: σ known or estimated? independent or paired samples?
- Interpret it in context (units, whether it contains 0 or 1)
- Take the 1 − α/2 quantile with the question’s level
- Compute estimate ± quantile × standard error
- Check that L < U
Solution
Correct order:
- Choose the pivot: σ known or estimated? independent or paired samples?
- Take the 1 − α/2 quantile with the question’s level
- Compute estimate ± quantile × standard error
- Check that L < U
- Interpret it in context (units, whether it contains 0 or 1)
They are the four questions of «Before handing in» in the order you do them.
If you want to halve the margin of error of an interval for the mean (same level), how much data do you need?
- Four times as much
- Twice as much
- Half as much
- The same, changing the level to 50 %
Solution
Answer: Four times as much
That is why the error is squared in the denominator of the sample-size formula: n = (z·σ/E)².
Try it in the R playground
Paste this script into the R playground and check that the exact belt interval hits as often as it promises, and the asymptotic one not quite:
set.seed(31)
n <- 12; lambda <- 0.05 # a belt that breaks down once every 20 h
r <- replicate(10000, {
x <- rexp(n, lambda); T <- sum(x); l <- n / T
ex <- qchisq(c(0.05, 0.95), 2 * n) / (2 * T)
as <- l + c(-1, 1) * qnorm(0.95) * l / sqrt(n)
c(exact = ex[1] <= lambda & lambda <= ex[2],
asymptotic = as[1] <= lambda & lambda <= as[2],
width_ex = diff(ex), width_as = diff(as))
})
round(rowMeans(r), 4)
What to look at:
exactis around 0.90: the level you asked for.asymptoticis also close to 0.90, but it misses more on one side than the other (count it as in the proofs).width_exandwidth_as: they are almost the same width; what changes is where they sit.- Replace
2 * nwithn(the mistake from my anecdote): the coverage of the exact one collapses.
Cheat sheet: confidence intervals
The essentials in 30 seconds: an interval is estimate ± quantile × standard error; the quantile is the one; with unknown σ and normal data, t; for variances, χ² and F with the quantiles swapped; with large n, the MLE ± z times its standard error; sample size, rounded up.
| I want… | Formula | In R |
|---|---|---|
| μ, known σ | mean(x) + c(-1, 1) * qnorm(1 - a/2) * sigma / sqrt(n) | |
| μ, unknown σ | t.test(x, conf.level = 1 - a)$conf.int | |
| σ² | , | (n - 1) * var(x) / qchisq(c(1 - a/2, a/2), n - 1) |
| σ² with μ known | , | sum((x - mu)^2) / qchisq(c(1 - a/2, a/2), n) |
| μ₁ − μ₂, known | qnorm | |
| μ₁ − μ₂, equal | t.test(x, y, var.equal = TRUE) | |
| μ₁ − μ₂, unequal | Welch | t.test(x, y) |
| Paired | t.test(x, y, paired = TRUE) | |
| σ₁²/σ₂² | , | var.test(x, y) |
| p | () | formula; prop.test(k, n) |
| p₁ − p₂ | prop.test(c(k1, k2), c(m, n)) | |
| Poisson λ | fitdist(x, "pois") + confint | |
| Exponential λ, asymptotic | , | fitdist(x, "exp") + confint |
| Exponential λ, exact | : | qchisq(c(a/2, 1 - a/2), 2 * n) / (2 * sum(x)) |
| θ uniform(0, θ) | : ; shortest | max(x) / c(1, a^(1/n)) |
| n for the mean | ceiling((qnorm(1 - a/2) * sigma / d)^2) | |
| n for p | ; with no data | ceiling((qnorm(1 - a/2) / (2 * d))^2) |
| Level | α | |
|---|---|---|
| 90 % | 0.10 | 1.645 |
| 95 % | 0.05 | 1.960 |
| 99 % | 0.01 | 2.576 |
| Symptom | Likely cause |
|---|---|
| L > U | quantiles not swapped for σ², the ratio or 1/λ |
| The 95 % interval comes out narrower than the theory’s | qnorm(0.95) or qt(0.95, …) instead of 0.975 |
| The exact exponential one is very wide | n degrees instead of 2n |
| Paired data that “show no difference” | they were treated as independent |
prop.test does not match the formula | continuity correction: that is normal |
| The size does not meet the margin | round instead of ceiling |
Before handing in, ask yourself:
- Have I used the quantile with the level of this part?
- Is σ known or am I estimating it? Are the two samples independent or paired?
- Is my L smaller than my U?
- Have I interpreted the interval in context (units, whether it contains 0 or 1)?
For your script
The topic’s code as functions, tested, ready for your .R file (no exercise statements). Each function returns the interval to two decimals; change d if you are asked for more.
# ---- Confidence intervals (ME1, topic 11) ----
# Mean of a normal: known sigma (z) or unknown (t)
ci_mean <- function(x, level = 0.95, sigma = NULL, d = 2) {
n <- length(x); a <- 1 - level
if (is.null(sigma)) e <- qt(1 - a / 2, n - 1) * sd(x) / sqrt(n)
else e <- qnorm(1 - a / 2) * sigma / sqrt(n)
round(mean(x) + c(-1, 1) * e, d)
}
# Variance and standard deviation of a normal (mu unknown)
ci_var <- function(x, level = 0.95, d = 2) {
n <- length(x); a <- 1 - level
v <- (n - 1) * var(x) / qchisq(c(1 - a / 2, a / 2), n - 1) # the big quantile at the bottom
round(rbind(variance = v, sd = sqrt(v)), d)
}
# Difference of means: known, equal (pooled) or unequal (Welch) variances
ci_diff <- function(x, y, level = 0.95, s1 = NULL, s2 = NULL, equal = TRUE, d = 2) {
m <- length(x); n <- length(y); a <- 1 - level; dif <- mean(x) - mean(y)
if (!is.null(s1)) {
e <- qnorm(1 - a / 2) * sqrt(s1^2 / m + s2^2 / n)
} else if (equal) {
sp2 <- ((m - 1) * var(x) + (n - 1) * var(y)) / (m + n - 2)
e <- qt(1 - a / 2, m + n - 2) * sqrt(sp2 * (1 / m + 1 / n))
} else {
return(round(as.numeric(t.test(x, y, conf.level = level)$conf.int), d))
}
round(dif + c(-1, 1) * e, d)
}
# Ratio of variances sigma1^2 / sigma2^2
ci_ratio <- function(x, y, level = 0.95, d = 2) {
r <- var(x) / var(y); a <- 1 - level
round(r / qf(c(1 - a / 2, a / 2), length(x) - 1, length(y) - 1), d)
}
# One proportion and two proportions (asymptotic, Wald)
ci_prop <- function(k, n, level = 0.95, d = 3) {
p <- k / n; a <- 1 - level
round(p + c(-1, 1) * qnorm(1 - a / 2) * sqrt(p * (1 - p) / n), d)
}
ci_two_prop <- function(k1, n1, k2, n2, level = 0.95, d = 3) {
p1 <- k1 / n1; p2 <- k2 / n2; a <- 1 - level
round((p1 - p2) + c(-1, 1) * qnorm(1 - a / 2) * sqrt(p1 * (1 - p1) / n1 + p2 * (1 - p2) / n2), d)
}
# Exponential: lambda (exact with chi^2(2n) and asymptotic) and its mean 1/lambda
ci_exp <- function(x, level = 0.95, d = 4) {
n <- length(x); T <- sum(x); l <- n / T; a <- 1 - level
ex <- qchisq(c(a / 2, 1 - a / 2), 2 * n) / (2 * T)
as <- l + c(-1, 1) * qnorm(1 - a / 2) * l / sqrt(n)
round(rbind(exact = ex, asymptotic = as, mean_exact = 1 / rev(ex),
mean_asymptotic = 1 / rev(as)), d)
}
# Poisson (asymptotic)
ci_pois <- function(x, level = 0.95, d = 3) {
a <- 1 - level; round(mean(x) + c(-1, 1) * qnorm(1 - a / 2) * sqrt(mean(x) / length(x)), d)
}
# Uniform(0, theta): the shortest interval with the maximum
ci_unif <- function(x, level = 0.95, d = 2) {
round(max(x) / c(1, (1 - level)^(1 / length(x))), d)
}
# Sample sizes (always round up)
n_mean <- function(sigma, delta, level = 0.95) ceiling((qnorm(1 - (1 - level) / 2) * sigma / delta)^2)
n_prop <- function(delta, p = 0.5, level = 0.95) ceiling((qnorm(1 - (1 - level) / 2) / delta)^2 * p * (1 - p))
# Simulated coverage of a method (returns the hit rate)
coverage <- function(generate, interval, value, B = 10000) {
mean(replicate(B, { ci <- interval(generate()); ci[1] <= value & value <= ci[2] }))
}
# Check with the exercise data
ci_mean(caliber, 0.90, sigma = 1.8)
ci_mean(caliber)
ci_var(caliber)
ci_ratio(drip, sprinkler, 0.90)
ci_diff(drip, sprinkler)
ci_exp(belt, 0.90)
ci_two_prop(18, 150, 29, 160, 0.99)
n_mean(1.8, 0.5)
set.seed(1)
coverage(function() rnorm(16, 20.5, 1.8), function(x) ci_mean(x, d = 6), 20.5, B = 2000)
Output:
[1] 19.97 21.45
[1] 19.95 21.48
[,1] [,2]
variance 1.13 4.96
sd 1.06 2.23
[1] 0.31 2.15
[1] -0.77 8.34
[,1] [,2]
exact 0.0294 0.0773
asymptotic 0.0267 0.0751
mean_exact 12.9397 34.0255
mean_asymptotic 13.3123 37.3846
[1] -0.165 0.043
[1] 50
[1] 0.96
The checks give the same as the solutions: (19.97, 21.45), (19.95, 21.48), the variance and standard deviation from exercise 1, (0.31, 2.15) and (−0.77, 8.34) from exercise 2, the belt intervals, the bonus and the 50 bananas. The last line measures the coverage of ci_mean with 2000 simulated samples: it is around 0.95.
What next?
This topic closes the ME1 theory: you can now describe data, compute probabilities, work with random variables and their sampling distributions, find estimators, judge them and, now, give a range with its confidence. That is exactly what goes into EC2, from the normal up to here.
To prepare for it, there is the exams and mock exams section, where the ME1 EC2 mock exam goes, with the R playground alongside as in the real exam. And if you want to review first, the theory, proofs and practice of this topic, and the properties of estimators, where the asymptotic normality of the MLE used by the large-sample intervals comes from.
What comes in ME2 starts where this ends: a hypothesis test is a confidence interval seen from the other side. The t = … and p-value = … lines we skipped today in the t.test output will take center stage.
Did this article help you? Here is how you can support SergioLearns →
Ready for the exam?ME1 EC2 mock exam — 4 hours with R beside you, from the normal to confidence intervals, four versions and a mark out of 50 (and why exercise 1 is worth double)


