Confidence intervals — from a number to a range, with bananas from two farms (and what 95 % really means)
When I showed my first interval to the packing-house manager, I told him that 95 % of the bunches weighed between 34.7 and 39 kilos, and he pulled a 28.8 one off the lorry. The scales were fine: I was the one who had got it wrong. That range was not about each bunch but about the mean weight of all the farm’s bunches, and a single bunch cannot prove you wrong about that. That day I learnt that a confidence interval takes five minutes to compute and five seconds to explain badly.
In point estimation we learnt to get a number for a parameter (the maximum likelihood or the method of moments estimator), and in the properties of estimators, to judge whether that number is good. But a number on its own does not say how far to trust it: 36.88 kilos from 15 bunches is not worth the same as from 1,500. Today we turn it into a range with a confidence level: the pivot method, the intervals for a normal (mean and variance), those for two populations, those for large samples (proportions, Poisson and exponential) and how much data you need for the range to be as narrow as you want. The full derivations, step by step, are in the confidence interval proofs.
In a nutshell: a confidence interval is a range (L, U) computed from the sample that, before you take it, contains the parameter with a fixed probability, the confidence level (for example, 95 %). It is built from a pivot, a quantity that depends on the sample and on the parameter and whose distribution is known (z, t, chi-squared or F), and its width shrinks with the square root of n.
Table of Contents
Before you start. For this topic you need three things you already have: knowing which estimator to use for each parameter ( for the mean, for the variance, the sample proportion for p), from point estimation; how those estimators are distributed, above all that , and that the t, the chi-squared and the F exist, from sampling distributions; and getting quantiles in R with qnorm, qt and qchisq. Nothing else. The topic goes in this order: first, what an interval is and what the 95 % really means; then, the recipe that builds them all (the pivot), applied to the mean of a normal (with z and with t) and to its variance (with chi-squared); next, two populations at once; then, large samples from any distribution; and finally, how much data you need for the range to be as narrow as you want. If you get lost, go back to the 15 bunches from Gáldar and their 36.88 ± 2.02: with them the whole topic makes sense.
Bananas from two farms
The example for the whole topic is a banana cooperative that receives bunches from two farms: one in Gáldar (Gran Canaria) and another in Tazacorte (La Palma). At the packing house every bunch is weighed, rejected bunches are noted (for blemishes or size) and the arrival time of each lorry is recorded. We will use five series (made up, but shaped like the real ones):
- Gáldar weights: the kilos of 15 bunches. They gather around a mean with no odd tails: normal .
- Tazacorte weights: the kilos of 12 bunches, also normal, .
- Before and after drip irrigation: the bunch weight of the same 10 Gáldar plants in the previous harvest and in the first one after switching to drip irrigation.
- Rejected: 23 out of 200 bunches from Gáldar and 31 out of 180 from Tazacorte. Each bunch, rejected or not: Bernoulli(p).
- Lorries: the minutes between one lorry and the next, 40 waits. Positive, with many short ones and a few long ones: exponential(λ).
galdar <- c(38.9, 36.7, 36.8, 28.8, 37.3, 38.6, 32.0, 34.0, 34.2, 36.0,
37.3, 36.4, 45.4, 39.6, 41.2) # kg
tazacorte <- c(32.6, 44.8, 30.8, 26.1, 28.9, 30.8, 39.9, 36.0, 34.7, 36.9,
29.7, 29.2) # kg
before <- c(36.5, 40.8, 38.6, 31.5, 34.0, 29.9, 31.7, 36.2, 34.8, 35.0)
after <- c(41.8, 41.8, 42.3, 32.9, 36.7, 31.0, 35.1, 39.4, 36.8, 39.0)
lorries <- c(2.9, 34.4, 5.2, 14.7, 0.1, 8.3, 92.7, 43.0, 5.3, 44.3, 0.5, 9.4,
11.3, 4.1, 37.5, 1.8, 27.6, 122.0, 3.9, 38.4, 5.2, 13.6, 0.7, 4.4,
58.4, 4.7, 27.4, 38.2, 46.0, 0.5, 12.4, 2.0, 17.2, 3.6, 37.6, 15.2,
58.0, 100.9, 54.6, 49.9) # minutes
round(c(n = length(galdar), mean = mean(galdar), s = sd(galdar)), 2)
Output:
n mean s 15.00 36.88 3.89
The point estimate of the Gáldar mean weight is kg, with a sample standard deviation kg. Is the true mean weight, , 36.88? Almost certainly not: another 15 bunches would give 37.4 or 36.1. The useful question is a different one: between which values is , and how sure are we?
From a number to a range: what a confidence interval is
Before the formula: build the range yourself
Before the definition, let’s build the range in our heads, with the 15 bunches from Gáldar and the σ = 4 kg that years of weighing tell us. The question that decides everything is: how much does the mean of 15 bunches move from one sample to another?
A single bunch strays from μ by about 4 kg. The mean of 15 strays much less, because heavy and light bunches cancel out when you average: its standard deviation is kg. That is the standard error. And since is normal, we know something very concrete: 95 % of the time it lands less than 1.96 standard errors from μ, that is, less than kg away.
Now comes the twist. “ is less than 2.02 kg from μ” is the same sentence as “μ is less than 2.02 kg from “: the distance from Gáldar to Tazacorte is the same as from Tazacorte to Gáldar. So if you stand at 36.88 and open 2.02 kg to each side, you catch μ in every sample where the mean landed close, which is 95 % of them.
| Step | What you know | Why |
|---|---|---|
| 1 | a bunch strays from μ by about 4 kg | σ = 4, from years of weighing |
| 2 | the mean of 15 strays by about 1.03 kg | : averaging cancels out the deviations |
| 3 | 95 % of the time, | is normal and |
| 4 | 95 % of the time, μ is between and | the distance from to μ is the same as from μ to |
| 5 | with this sample, (34.86, 38.90) | 36.88 − 2.02 = 34.86 and 36.88 + 2.02 = 38.90 |
You now have a whole confidence interval, without a single definition. What comes next is giving it its official names: the two ends are L and U, the 95 % is the confidence level ( with ) and the 1.96 is a quantile. The sentence in step 4, written with probabilities, is exactly the formal definition.
A confidence interval for a parameter θ is a pair of functions of the sample, and , such that
The number is the confidence coefficient and the confidence level: with , a 95 % interval. L and U are called the lower and upper confidence limits.
What matters is what is random. θ is a fixed number (the mean weight of Gáldar bunches, which nobody knows); L and U are random, because they depend on the sample. Before you weigh the bunches, the range (L, U) is a random variable with two ends that will land somewhere. After you weigh them you have two numbers, for example (34.86, 38.90), and nothing is random any more.
Look at the drawing: the range is centred on the point estimate and opens a margin of error on each side. Almost every interval in this topic has that shape:
A good interval does two things at once: is high and the range is narrow. They pull in opposite directions: if you want more confidence, the range widens. The only way to have both is more data.
With discrete variables (proportions, counts) you sometimes cannot get exactly : then you ask for . That is why the intervals for proportions are called approximate.
What 95 % means
This is the part that gets explained wrong most often (by me first). The 95 % is not the probability that μ is inside your range (34.86, 38.90): μ is either in or out, and there is nothing left to chance. The 95 % is a property of the method: if you repeated the sampling many times and with each sample computed an interval with the same recipe, 95 % of those intervals would contain μ.
One way to picture it: think of a net thrown at a fish that does not move. The fish is μ, still in its place. The net is your interval, and each sample throws it somewhere different. Before throwing you can say “this net catches the fish 95 times out of 100”. After throwing, the net is in the water: either the fish is inside or it is not, and the 95 % no longer talks about this net, but about how you throw it.
| Question | Before weighing the bunches | After weighing them |
|---|---|---|
| What is random? | , and with it L and U | nothing: you have two numbers |
| What is fixed? | μ (unknown) | μ (unknown) and the range (34.86, 38.90) |
| Which probability makes sense? | none: it is 1 or 0, but you do not know which | |
| How do you say it? | “the method gets it right 95 % of the time” | “95 % confidence that μ is in (34.86, 38.90)” |
That is why we say “confidence” and not “probability”: the new word keeps the method’s 95 % and lends it to the specific range, without pretending that μ is drawn at random.
R lets us do what we cannot do on the farm: make up a true mean weight (μ = 38 kg, σ = 4), draw 100 samples of 15 bunches and compute the interval of each.
set.seed(2024)
mu <- 38; sigma <- 4; n <- 15
ci <- t(replicate(100, {
x <- rnorm(n, mu, sigma) # 15 made-up bunches
mean(x) + c(-1, 1) * qnorm(0.975) * sigma / sqrt(n) # their 95 % interval
}))
inside <- ci[, 1] < mu & mu < ci[, 2] # does the range contain 38?
sum(inside) # how many of the 100 hit
which(!inside) # which ones miss
Output:
[1] 96 [1] 35 66 68 79
How to read it
ciis a matrix with 100 rows and 2 columns: each row, the interval of one sample.t()puts it that way becausereplicatestores each interval in a column.sum(inside)counts theTRUEs: 96 of the 100 intervals contain 38. We expected about 95; 96 is one of the normal counts with only 100 repetitions (with 10,000 it would get much closer to 95 %, as you will see in the practice).which(!inside)gives the unlucky samples: 35, 66, 68 and 79. In those, the mean of the 15 bunches came out so low (or so high) that the range fell short.
In the drawing, each horizontal bar is the interval of one sample and the vertical line is the true 38. All bars have the same length (with known σ the margin does not change) and what moves is their center. The four in coral do not touch 38. On the farm you only see one bar, and you do not know whether it is a grey one or a coral one. What you do know is that the recipe hits 95 times out of 100: that is confidence.
Saying “there is a 95 % probability that μ is between 34.86 and 38.90”. With the numbers already computed, μ is in or out (probability 1 or 0). The right wording: “we are 95 % confident that μ is between 34.86 and 38.90”, because the method hits in 95 % of samples.
Mixing up the interval for the mean with the range of the data, which was my mistake with the manager. The interval for μ is about the mean weight; a single 28.8 kg bunch falls outside without contradicting anything. Individual bunches spread much more: with σ = 4, roughly 95 % of them lie within μ ± 8.
Check you’ve got it: twenty classmates each compute their own 90 % interval with their own 15 bunches. How many of the twenty ranges contain μ?
You cannot know, and that is the right answer. What you do know is what happens on average: before weighing, each range is right with probability 0.9, so you expect hits. It could come out as 17, 19 or all 20 (all of them being right has probability ). And none of the twenty can say “mine has a 90 % probability of containing μ”: each specific range is right or wrong, and its owner does not know which of the two they got.
The pivot method
Where do L and U come from? From the pivot method, the recipe for the whole topic. A pivot is a quantity that:
- depends on the sample and on the parameter θ (and on nothing else unknown), and
- has a distribution that does not depend on θ: an N(0, 1), a t, a chi-squared or an F, with their tables and their
q…in R.
With a pivot, the procedure is four steps:
- Take a good estimator of θ (usually the maximum likelihood one).
- Find a function of θ and whose distribution does not depend on θ: the pivot Q.
- Find a and b with , leaving in each tail: a is the quantile and b the quantile.
- Solve for θ in the double inequality . Whatever is left to the left of θ is L, and to the right, U.
Step 4 is algebra, but it is where mistakes happen: when you multiply by something negative or divide, the inequalities flip, and the quantiles with them. You will see it with the variance.
The four steps, with the Gáldar bunches
Before applying the recipe to each case, look at it once in full with the range you built by hand at the start (the Gáldar mean with σ = 4). That way you see the 2.02 kg did not come out of nowhere: it was these four steps.
| Step | What you do | With Gáldar | Why |
|---|---|---|---|
| 1. Estimator | you choose | , which gave 36.88 | it is the MLE of μ and its distribution is known |
| 2. Pivot | you mix and θ into a quantity with a known distribution | subtracting μ centres it at 0 and dividing by leaves it with standard deviation 1: it no longer depends on μ | |
| 3. Quantiles | you look for a and b with | a = −1.96 and b = 1.96 | 2.5 % in each tail: qnorm(0.025) and qnorm(0.975) |
| 4. Solving | you isolate θ in the middle | , that is, (34.86, 38.90) | each operation on all three sides at once (you will see it step by step in the mean of a normal) |
The key is step 2, and it is the hardest one to see. Why is on its own not enough? Because its distribution, , depends on μ, which you do not know: you cannot look up its quantiles. By subtracting μ and dividing by you turn it into something whose table is in every book. That is the double condition of a pivot: it has to contain θ (so you can solve for it later) and its distribution cannot depend on θ (so you can find a and b).
If the exam asks for an interval “by the pivot method”, write the four steps with their names even if it looks obvious. That way you skip none, and it forces you to say which distribution the pivot has before looking up the quantile.
The mean of a normal
With a simple random sample from , the estimator of μ is and, as we saw in sampling distributions, .
Known σ: the z
If σ is known (at the cooperative, years of weighing say that the Gáldar standard deviation is σ = 4 kg), the pivot is
and solving for μ in gives
where is the standard normal quantile that leaves to its right: qnorm(1 - alpha/2). At 95 %, qnorm(0.975) = 1.96.
sigma <- 4; n <- length(galdar); alpha <- 0.05 z <- qnorm(1 - alpha / 2) # 1.96: leaves 0.025 to the right margin <- z * sigma / sqrt(n) # margin of error round(c(z = z, margin = margin, L = mean(galdar) - margin, U = mean(galdar) + margin), 2)
Output:
z margin L U 1.96 2.02 34.86 38.90
How to read it
z= 1.96: the 0.975 quantile of N(0, 1). We use 0.975 and not 0.95 because the 5 % left out is split into two 2.5 % tails.margin= 2.02 kg: how far the range opens on each side of the mean. It is .L= 34.86 andU= 38.90: with 95 % confidence, the mean weight of Gáldar bunches is between 34.86 and 38.90 kg. Check: 36.88 − 2.02 = 34.86 and 36.88 + 2.02 = 38.90.
Solving the inequality, step by step
The interval formula comes from solving for μ in a double inequality. There is just one rule: whatever you do, do it on all three sides at once. And there is a trap: if you multiply by a negative number, both signs flip.
| Step | What is left | Why |
|---|---|---|
| 0 | the pivot between its two quantiles, with probability 0.95 | |
| 1 | multiply by , which is positive: the signs stay the same | |
| 2 | subtract on all three sides, so only μ is left in the middle | |
| 3 | multiply by −1: every sign changes and the become | |
| 4 | the same inequality read from right to left, with the small one first |
None of these steps changes the probability: they are the same statement written another way, so the last one also holds with probability 0.95. Whatever is left to the left of μ is L and to the right, U.
The step people forget most is step 3. If you do not flip the signs, you end up with L = 38.90 and U = 34.86, a lower limit bigger than the upper one. With the mean you notice at once; with the variance the same thing happens, but when flipping a fraction, and there it is easier to go wrong.
Unknown σ: the t
Usually σ is not known. Then it is replaced by the sample standard deviation S (the one with divisor n − 1, which sd() gives), and the pivot changes distribution:
It is the result from sampling distributions: a standard normal divided by the square root of a chi-squared over its degrees of freedom. The interval has the same shape, with the t quantile:
In the drawing, t(14) has heavier tails than the normal, so to leave 2.5 % to the right you have to go further: 2.14 instead of 1.96. That is the price of not knowing σ: the range widens. With large n the t looks so much like the normal that the two quantiles almost coincide.
Why does the distribution change if we only swapped σ for S? Because S also comes from the sample. With σ, the denominator of the pivot is a fixed number and the only thing that moves is . With S both things move: in some samples S comes out small by chance, the denominator shrinks and T shoots up. Those samples are what fatten the tails, and to cover 95 % you have to go further than 1.96.
| What you look at | σ known | σ unknown | What has changed |
|---|---|---|---|
| Pivot | σ, fixed, becomes S, random | ||
| Distribution | N(0, 1) | t(14) | the t pays for the uncertainty in S |
| Deviation in the margin | σ = 4 | s = 3.888 | the one from this sample |
| 95 % quantile | 1.96 | 2.145 | heavier tails, quantile further out |
| Margin | quantile times standard error, as always | ||
| Interval | (34.86, 38.90) | (34.73, 39.03) | the center does not change: 36.88 |
The price of not knowing σ depends on n. The 0.975 quantiles of the t, qt(0.975, n – 1), are 2.78 with n = 5; 2.14 with n = 15; 2.05 with n = 30 and 1.98 with n = 100. With little data the difference from 1.96 is large; with a hundred, you barely notice it.
Using 1.96 because “the data are normal” when the problem does not give you σ. What decides between z and t is not whether the data are normal (in both cases they are), but whether σ is given in the problem or you have to get it from the sample.
In R, t.test does all the arithmetic:
t.test(galdar, conf.level = 0.95)
Output:
One Sample t-test
data: galdar
t = 36.735, df = 14, p-value = 2.532e-15
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
34.72673 39.03327
sample estimates:
mean of x
36.88
How to read it
The t.test output has more than we asked for (the hypothesis test, which is ME2 material). For the interval, line by line:
data: galdar: the sample used.t = 36.735, df = 14, p-value = …: the statistic of a test of “μ = 0”, which makes no sense here (nobody thinks a bunch weighs 0 kg). From this line we only needdf = 14: the degrees of freedom, n − 1.95 percent confidence interval: 34.72673 39.03327: the interval. To two decimals, (34.73, 39.03) kg.mean of x 36.88: the point estimate, the center of the range.
The t range, (34.73, 39.03), is 0.26 kg wider than the z one, (34.86, 38.90). Check the margin: , and 36.88 ± 2.15. To keep only the interval, t.test(galdar)$conf.int.
t.test(x)$conf.int is the quickest way to check in the exam an interval you have done by hand with qt. If they do not match, it is almost always because you used qt(0.95, …) instead of qt(0.975, …).
Check you’ve got it: if with the same 15 bunches the sample standard deviation had come out as s = 3, would the t range be wider or narrower than the z one with σ = 4?
Narrower. The t margin would be kg, less than the 2.02 from z. The t quantile is always bigger than 1.96, but the margin is quantile times deviation, and in this sample s would have come out quite a bit smaller than σ. What you can say is that, with 15 bunches, the t method gives wider ranges on average; in one specific sample it can go the other way.
The variance of a normal
How much does the weight vary from one bunch to another? For the estimator is and the pivot is the one from sampling distributions:
With and the chi-squared quantiles, . When you solve for you have to flip the fraction, and the inequality reverses: the big quantile goes to the lower limit.
The drawing shows what sets this interval apart from the previous ones: the chi-squared is not symmetric, so its two quantiles are not the same distance from the center, and the interval for is not centred on .
n <- length(galdar); s2 <- var(galdar) q <- qchisq(c(0.975, 0.025), df = n - 1) # big one first: it goes at the bottom ci_var <- (n - 1) * s2 / q round(c(s2 = s2, q_big = q[1], q_small = q[2]), 3) round(ci_var, 2) # interval for sigma^2 (kg^2) round(sqrt(ci_var), 2) # interval for sigma (kg)
Output:
s2 q_big q_small 15.119 26.119 5.629 [1] 8.1 37.6 [1] 2.85 6.13
How to read it
s2= 15.119: the sample variance, in kg².q_big= 26.119 andq_small= 5.629: the 0.975 and 0.025 quantiles of χ²(14). Notice they are not symmetric: χ²(14) has mean 14, and 26.1 is 12.1 above it while 5.6 is 8.4 below.- The interval for is (8.10, 37.60) kg². Check: , and 211.67/26.119 = 8.10 and 211.67/5.629 = 37.60.
- Its square root, (2.85, 6.13) kg, is the interval for σ: with 95 % confidence, the standard deviation of Gáldar bunch weights is between 2.85 and 6.13 kg. As the square root is increasing, you just take the root of both ends.
With 15 bunches the interval for the variance is wide (the upper end is more than four times the lower one). Estimating spread needs much more data than estimating the mean.
The sigma.test function from the TeachingDemos package does the same, like t.test for the mean:
library(TeachingDemos) galdar <- c(38.9, 36.7, 36.8, 28.8, 37.3, 38.6, 32.0, 34.0, 34.2, 36.0, 37.3, 36.4, 45.4, 39.6, 41.2) sigma.test(galdar, conf.level = 0.95)$conf.int
Output:
[1] 8.103849 37.604246 attr(,"conf.level") [1] 0.95
The same 8.10 and 37.60 (here with more decimals; attr(,"conf.level") just reminds you of the level you asked for).
Putting the small quantile in the lower limit. You get as L and 8.10 as U: an “interval” whose lower limit is bigger than its upper one. If your L is bigger than your U, you have flipped the quantiles.
Solving for the variance, step by step
Here the algebra is different from the mean: is in the denominator, so at some point you have to flip the fraction. The rule that controls everything: if two positive numbers satisfy , their reciprocals satisfy (2 is less than 4, but 1/2 is more than 1/4). With the Gáldar numbers, :
| Step | What is left | Why |
|---|---|---|
| 0 | the pivot between the 0.025 and 0.975 quantiles of χ²(14) | |
| 1 | flip all three sides: they are all positive and the become | |
| 2 | multiply by 211.67, which is positive: the signs stay | |
| 3 | do both divisions and read from right to left |
Notice where each quantile ends up: the small one, 5.629, was on the left in step 0 and ends up giving the upper limit, 37.60. It is not a rule to memorise, it is what happens when you divide: dividing by a small number gives a big result.
And why is the range not centred on ? It goes 7.02 kg² below (15.12 − 8.10) and 22.48 kg² above (37.60 − 15.12). The chi-squared has its long tail on the right, and flipping the fraction carries that asymmetry over to the interval. That is why there is no “estimate ± margin” here: it is the exception to the general shape from the start of the topic.
Check you’ve got it: with the same bunches, what is the 90 % interval for σ²? The 0.05 and 0.95 quantiles of χ²(14) are 6.571 and 23.685.
(8.94, 32.21) kg². At 90 % you leave 5 % in each tail, which is why you use the 0.05 and 0.95 quantiles. The big one goes to the lower limit, , and the small one to the upper limit, . It is narrower than the 95 % one, (8.10, 37.60), because you ask for less confidence. Its square root, (2.99, 5.68) kg, is the 90 % interval for σ.
Two farms: comparing means
Do Gáldar bunches weigh more than Tazacorte ones? With from and from , independent, the parameter is the difference and the estimator, . There are three cases depending on what is known about the variances, and a fourth when the samples are not independent.
m <- length(galdar); n <- length(tazacorte)
round(c(m = m, n = n, mean_G = mean(galdar), mean_T = mean(tazacorte),
diff = mean(galdar) - mean(tazacorte), s_G = sd(galdar), s_T = sd(tazacorte)), 2)
Output:
m n mean_G mean_T diff s_G s_T 15.00 12.00 36.88 33.37 3.51 3.89 5.33
The difference between the means is 3.51 kg in favour of Gáldar. The question is whether it is a real difference or sampling noise.
Known variances
If and are known (here 4 and 4.5 kg, from years of weighing), since is normal:
se <- sqrt(4^2 / m + 4.5^2 / n) # standard error of the difference round((mean(galdar) - mean(tazacorte)) + c(-1, 1) * qnorm(0.975) * se, 2)
Output:
[1] 0.26 6.77
Unknown but equal variances
If you assume without knowing it, you estimate it with the pooled variance, an average of the two variances weighted by their degrees of freedom:
and the pivot is a t with degrees of freedom:
Unknown and unequal variances
If you cannot assume they are equal, the pivot is no longer an exact t, but it is approximated by a t with degrees of freedom that R works out (the Welch approximation). In R, both cases are a two-sample t.test with var.equal:
t.test(galdar, tazacorte, var.equal = TRUE)$conf.int # equal (pooled) t.test(galdar, tazacorte)$conf.int # unequal (Welch)
Output:
[1] -0.1370754 7.1637421 attr(,"conf.level") [1] 0.95 [1] -0.321763 7.348430 attr(,"conf.level") [1] 0.95
How to read it
Three intervals for the same 3.51 kg difference:
| Case | 95 % interval | Contains 0? |
|---|---|---|
| Known σ (4 and 4.5) | (0.26, 6.77) | No |
| Unknown and equal | (−0.14, 7.16) | Yes, just |
| Unknown and unequal (Welch) | (−0.32, 7.35) | Yes |
- The first does not contain 0: if the standard deviations really were 4 and 4.5, the data would say Gáldar bunches weigh more on average (between 0.26 and 6.77 kg more).
- The other two do contain 0: without knowing σ, the difference could be 0 (or even negative) with 95 % confidence. With 15 and 12 bunches and a sample standard deviation of 5.33 kg in Tazacorte, it is not enough to claim Gáldar’s weigh more.
- Welch is the widest: assuming nothing about the variances costs degrees of freedom (19.6 instead of 25).
“the interval contains 0” reads as “at this confidence level, the data do not let us say the means differ”. It is not the same as “the means are equal”. If the interval for lies entirely above 0, the first mean is larger; entirely below, smaller.
Paired data: before and after drip irrigation
The 10 Gáldar plants were weighed in the previous harvest and in the first one with drip irrigation. Here the two samples are not independent: each “after” goes with its “before” (the same plant, the same soil, the same shade). You work with the differences , which are a single sample, and use the t interval for their mean :
d <- after - before round(d, 1) t.test(after, before, paired = TRUE)$conf.int # right: paired t.test(after, before)$conf.int # wrong: as if independent
Output:
[1] 5.3 1.0 3.7 1.4 2.7 1.1 3.4 3.2 2.0 4.0 [1] 1.775213 3.784787 attr(,"conf.level") [1] 0.95 [1] -0.6292924 6.1892924 attr(,"conf.level") [1] 0.95
How to read it
d: every plant gained weight (all differences are positive, from 1 to 5.3 kg).- Paired: (1.78, 3.78). With 95 % confidence, drip irrigation raises the mean bunch weight by between 1.78 and 3.78 kg. It does not contain 0.
- Treated as independent: (−0.63, 6.19), which does contain 0. Why such a change? The plants are very different from each other (from 29.9 to 40.8 kg before drip irrigation), and that between-plant variation, which pairing removes, leaks into the standard error if you ignore the pairing.
Treating as independent data that come from the same individuals (before and after, a person’s two eyes, two measurements on the same machine). Check whether each value in one sample “has a partner” in the other: if it does, paired = TRUE.
The ratio of variances
To choose between the pooled t and Welch it helps to check first whether the variances can be assumed equal. The parameter is and the pivot, the F from sampling distributions:
Solving for the ratio (and flipping the quantiles again):
var.test(galdar, tazacorte, conf.level = 0.90)
Output:
F test to compare two variances
data: galdar and tazacorte
F = 0.53316, num df = 14, denom df = 11, p-value = 0.2671
alternative hypothesis: true ratio of variances is not equal to 1
90 percent confidence interval:
0.1946807 1.3678256
sample estimates:
ratio of variances
0.5331619
How to read it
F = 0.53316, num df = 14, denom df = 11: the ratio of the two sample variances, , with 14 and 11 degrees of freedom ( and , in that order).p-valueandalternative hypothesis: the test, ME2 material.90 percent confidence interval: 0.1946807 1.3678256: the interval for the ratio, (0.19, 1.37). It contains 1, so with 90 % confidence the two variances may be equal, and the pooled t is reasonable.ratio of variances 0.5331619: the point estimate of the ratio.
Notice how wide it is: the ratio could go from a fifth to almost one and a half. With small samples, comparing variances gives little information.
Large samples: proportions, Poisson and exponential
Outside the normal there is hardly ever an exact pivot at hand. Then we use what we saw in the properties of estimators: with large n (in practice ), the maximum likelihood estimator is approximately normal, with mean θ and a variance that is estimated. The approximate pivot is
Only the standard error changes:
| Population | Estimator | Standard error | Approximate interval |
|---|---|---|---|
| Any, mean μ | |||
| Bernoulli(p) | |||
| Poisson(λ) | |||
| Exponential(λ) |
One proportion: the rejected bunches
Out of 200 Gáldar bunches, 23 were rejected: . For the normal approximation to be good you need and : here 23 and 177, plenty.
n <- 200; rejected <- 23 p <- rejected / n round(p + c(-1, 1) * qnorm(0.975) * sqrt(p * (1 - p) / n), 3) # by hand (Wald) prop.test(rejected, n, conf.level = 0.95)$conf.int # with prop.test
Output:
[1] 0.071 0.159 [1] 0.07581489 0.16949788 attr(,"conf.level") [1] 0.95
How to read it
- By hand: (0.071, 0.159). With 95 % confidence, between 7.1 % and 15.9 % of Gáldar bunches are rejected.
prop.test: (0.076, 0.169). Different in the third decimal becauseprop.testuses another method (Wilson’s, with continuity correction), which is not symmetric around 0.115 and does better with small samples or proportions close to 0 or 1. In the exam, if you are asked for “the asymptotic interval”, it is the formula one;prop.testis there to compare.
If the data come as zeros and ones (1 = rejected), n is length(x) and is mean(x). For prop.test you need the number of successes: sum(x).
Two proportions
In Tazacorte 31 out of 180 were rejected (). For the difference , the standard errors add in squares, as with means:
p1 <- 23 / 200; p2 <- 31 / 180 round((p1 - p2) + c(-1, 1) * qnorm(0.975) * sqrt(p1 * (1 - p1) / 200 + p2 * (1 - p2) / 180), 3) prop.test(c(23, 31), c(200, 180))$conf.int
Output:
[1] -0.128 0.013 [1] -0.1331915 0.0187471 attr(,"conf.level") [1] 0.95
The interval, (−0.128, 0.013), contains 0: although in the sample Tazacorte rejects 5.7 points more, with 95 % confidence the data do not let us say that the two farms reject in different proportions. prop.test gives a slightly wider range because of the correction.
Poisson and exponential: the lorries
The waits between lorries are exponential with rate λ (lorries per minute). The maximum likelihood estimator is and, by the properties of the MLE, its asymptotic variance is .
n <- length(lorries) lambda <- 1 / mean(lorries) round(c(n = n, mean = mean(lorries), lambda = lambda), 4) round(lambda + c(-1, 1) * qnorm(0.975) * lambda / sqrt(n), 4) # asymptotic round(qchisq(c(0.025, 0.975), 2 * n) / (2 * sum(lorries)), 4) # exact
Output:
n mean lambda 40.0000 26.4475 0.0378 [1] 0.0261 0.0495 [1] 0.0270 0.0504
How to read it
- 40 waits with mean 26.45 minutes, so lorries per minute (about 2.3 lorries an hour).
- The asymptotic one, (0.0261, 0.0495), is symmetric: .
- The last line is an exact interval: it comes from , a pivot that does not need large n and that is derived step by step in the proofs (it comes up in EC2). It gives (0.0270, 0.0504), very close, because 40 is already quite a lot.
- For the mean time between lorries, , just invert the ends (the function is decreasing, so they also swap places): (1/0.0504, 1/0.0270) = (19.84, 37.02) minutes.
For the Poisson it is the same with , and fitdist (from the fitdistrplus package, which we used in point estimation) gives the MLE, its standard error and, with confint, the asymptotic interval of any model:
suppressMessages(library(fitdistrplus))
lorries <- c(2.9, 34.4, 5.2, 14.7, 0.1, 8.3, 92.7, 43.0, 5.3, 44.3, 0.5, 9.4, 11.3, 4.1, 37.5, 1.8,
27.6, 122.0, 3.9, 38.4, 5.2, 13.6, 0.7, 4.4, 58.4, 4.7, 27.4, 38.2, 46.0, 0.5, 12.4, 2.0,
17.2, 3.6, 37.6, 15.2, 58.0, 100.9, 54.6, 49.9)
fit <- fitdist(lorries, "exp")
round(fit$estimate, 4); round(fit$sd, 4)
round(confint(fit), 4)
Output:
rate
0.0378
rate
0.006
2.5 % 97.5 %
rate 0.0261 0.0495
estimate is , sd its standard error (0.006 = 0.0378/√40) and confint the 95 % asymptotic interval, the same as by hand.
How many bunches must we weigh? Sample size
The margin of error of the interval for the mean is . If we want it not to exceed an amount δ, we just solve for n:
If σ is not known, you plug in the S of a pilot sample (or of earlier studies). For a proportion, the margin is and you get . As we do not know p before taking the sample, we use the worst case: never exceeds 1/4, so
z <- qnorm(0.975)
round(c(mean = (z * 4 / 1)^2, prop_worst = (z / (2 * 0.03))^2,
prop_pilot = (z / 0.03)^2 * 0.115 * (1 - 0.115)), 2)
ceiling(c((z * 4 / 1)^2, (z / (2 * 0.03))^2, (z / 0.03)^2 * 0.115 * (1 - 0.115)))
Output:
mean prop_worst prop_pilot
61.46 1067.07 434.40
[1] 62 1068 435
- To estimate the Gáldar mean weight with an error of at most 1 kg at 95 % (σ = 4): , so 62 bunches. Always round up: with 61 the margin would be slightly above 1.
- For the proportion of rejected bunches with a 3-point error, knowing nothing about p: 1068 bunches. With the pilot estimate 0.115, 435 are enough: knowing p saves a lot.
- In the drawing, the margin falls with the square root of n: half the margin takes four times the data.
Solving for n, step by step
Solving for n is easier than solving for μ, because everything is positive and no sign flips. The question, in words: how many bunches do we need for the range to open at most 1 kg on each side?
| Step | What is left | Why |
|---|---|---|
| 0 | the margin (quantile times standard error) cannot go over δ = 1 | |
| 1 | multiply by , which is positive: the sign stays | |
| 2 | the arithmetic: 1.96 · 4 = 7.84 | |
| 3 | square both sides: both are positive and the order is kept (with the rounded 1.96 you get 61.47; R, with the exact quantile, gives 61.46) | |
| 4 | n = 62 | n is a whole number and the inequality asks for “at least”: round up |
Why up and not to the nearest? Check it: with 61 bunches the margin is kg, which goes over the 1 you asked for; with 62 it drops to 0.9957 kg. Rounding down always breaks the requirement, even if only by a little.
And the 1/4 for proportions: is 0 at p = 0 and at p = 1, and it peaks right in the middle. With p = 0.1 it is 0.09; with the pilot, 0.115, it is 0.10; with p = 0.3, 0.21; and with p = 0.5, 0.25. If you know nothing about p, using 1/4 means taking the worst case: the n you get works for any p. That is why the pilot saves so much: 0.10 against 0.25 leaves n at less than half (435 against 1068).
Check you’ve got it: how many bunches do you need for a margin of 0.5 kg at 99 % with σ = 4?
You need 425. At 99 % you leave 0.5 % in each tail, so the quantile is qnorm(0.995) = 2.576. Then (with R’s exact quantile, 424.63), and rounding up, 425. Compare it with the 246 at 95 % for the same margin: raising the confidence also costs data, because the quantile grows.
How I choose the interval
In the exam, the hard part is usually not the arithmetic but choosing the formula. These questions, in this order, take you to the right one:
| If you are asked about… | and you know that… | Pivot | In R |
|---|---|---|---|
| μ of a normal | σ known | Z | qnorm |
| μ of a normal | σ unknown | t(n − 1) | t.test(x) |
| σ² or σ of a normal | — | χ²(n − 1) | qchisq, sigma.test |
| μ₁ − μ₂, normals | σ₁, σ₂ known | Z | qnorm |
| μ₁ − μ₂, normals | unknown and equal | t(m + n − 2) | t.test(x, y, var.equal = TRUE) |
| μ₁ − μ₂, normals | unknown and unequal | Welch’s t | t.test(x, y) |
| μ₁ − μ₂ | paired data | t(n − 1) of the differences | t.test(x, y, paired = TRUE) |
| σ₁²/σ₂², normals | — | F(m − 1, n − 1) | var.test(x, y) |
| p (or p₁ − p₂) | large n | approximate Z | formula, prop.test |
| Poisson or exponential λ, any MLE | large n | approximate Z | formula, fitdist + confint |
| λ of an exponential | small n | χ²(2n) | qchisq |
What is proved in this topic
Each interval has its full derivation in the confidence interval proofs:
| Result | Idea of the proof |
|---|---|
| Interval for μ with known σ | solve for μ in |
| Interval for μ with unknown σ | with Z and V independent |
| Interval for σ² | solve inside the χ²: the quantiles swap places |
| Intervals for μ₁ − μ₂ (known and pooled) | the sum of two independent χ² is a χ² |
| Interval for the ratio of variances | solve inside the F |
| Exact interval for λ of an exponential | and |
| Interval for θ of a uniform(0, θ) | the pivot has distribution |
| Sample sizes | solve for n from the margin; |
Common mistakes
- Reading the interval as a probability about μ. Once the range is computed, μ is in or out. The 95 % belongs to the method.
- Mixing up the interval for the mean with the range of the data. The range for μ is much narrower than the cloud of bunches.
- Using
qnorm(0.95)for a 95 % interval. It isqnorm(0.975): the 5 % is split into two tails. Same withqt,qchisqandqf. - Using z with unknown σ and small n. With S and 15 values the quantile is that of t(14), 2.14, not 1.96.
- Quantiles the wrong way round in σ² and in the ratio. When you flip the fraction, the big quantile goes to the lower limit.
- Treating paired data as independent. Before and after on the same plant are analysed through the differences.
- Rounding the sample size down. 61.46 means 62 bunches, never 61.
Try it in the R playground
Paste this script into the R playground and run it all. It repeats the 100-interval experiment with the t and another sample size:
set.seed(7)
mu <- 38; sigma <- 4; n <- 8 # change n and the level and run again
level <- 0.95
ci <- t(replicate(100, {
x <- rnorm(n, mu, sigma)
t.test(x, conf.level = level)$conf.int
}))
inside <- ci[, 1] < mu & mu < ci[, 2]
sum(inside)
plot(NULL, xlim = range(ci), ylim = c(1, 100), xlab = "kg", ylab = "sample")
segments(ci[, 1], 1:100, ci[, 2], 1:100, col = ifelse(inside, "grey50", "red"))
abline(v = mu, lwd = 2)
What to look at:
- In the Environment tab,
ciis a 100 × 2 matrix: one interval per row. sum(inside)is around 95, even though n is 8: the t corrects for σ being unknown.- In Plots, the bars now have different lengths: with unknown σ, each sample brings its own S.
- Change
levelto 0.80: the bars get shorter and about 20 out of 100 miss. - Replace
t.test(x, …)$conf.intwithmean(x) + c(-1, 1) * qnorm(0.975) * sd(x) / sqrt(n)with n = 8: you will see more red bars than there should be.
Summary
| Interval | Formula | With the bananas |
|---|---|---|
| μ, known σ | (34.86, 38.90) kg | |
| μ, unknown σ | (34.73, 39.03) kg | |
| σ² | (8.10, 37.60) kg² | |
| μ₁ − μ₂, pooled | (−0.14, 7.16) kg | |
| Paired | (1.78, 3.78) kg | |
| σ₁²/σ₂² (90 %) | (0.19, 1.37) | |
| p | (0.071, 0.159) | |
| Exponential λ | (0.0261, 0.0495) | |
| Size for the mean | 62 bunches |
Three ideas to take away:
- The 95 % belongs to the method, not to your range. Out of 100 samples, about 95 intervals contain the parameter; yours is one of them or it is not, and you do not know which.
- Everything comes from the pivot. Find a quantity with a known distribution that contains the parameter, cut off both tails with its quantiles and solve. If you flip a fraction while solving, flip the quantiles too.
- The width falls with the square root of n. Half the margin takes four times the data: that is where sample size comes from.
Now it is time to derive it: in the confidence interval proofs each interval is worked out step by step, including the exact exponential pivot that comes up in EC2. Then, in the confidence intervals practice, you will simulate it all in R, plots included. And to check you have got it, the confidence intervals exercises go from easy to hard and come with commented solutions.
Next step: proofsConfidence intervals — step-by-step proofs with the pivot method (and why the quantiles swap places)Did this article help you? Here is how you can support SergioLearns →



