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.

Before you start. For this topic you need three things you already have: knowing which estimator to use for each parameter (Xˉ \bar X for the mean, S2 S^2 for the variance, the sample proportion for p), from point estimation; how those estimators are distributed, above all that Xˉ∼N(μ,σ/n) \bar X \sim N(\mu, \sigma/\sqrt n) , 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 N(μ1,σ1) N(\mu_1, \sigma_1) .
  • Tazacorte weights: the kilos of 12 bunches, also normal, N(μ2,σ2) N(\mu_2, \sigma_2) .
  • 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 xˉ=36.88 \bar x = 36.88 kg, with a sample standard deviation s=3.89 s = 3.89 kg. Is the true mean weight, μ1 \mu_1 , 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 μ1 \mu_1 , 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 σ/n=4/15=1.03 \sigma/\sqrt n = 4/\sqrt{15} = 1.03 kg. That is the standard error. And since Xˉ \bar X is normal, we know something very concrete: 95 % of the time it lands less than 1.96 standard errors from μ, that is, less than 1.96⋅1.03=2.02 1.96 \cdot 1.03 = 2.02 kg away.

Now comes the twist. “Xˉ \bar X is less than 2.02 kg from μ” is the same sentence as “μ is less than 2.02 kg from Xˉ \bar X “: 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.

StepWhat you knowWhy
1a bunch strays from μ by about 4 kgσ = 4, from years of weighing
2the mean of 15 strays by about 1.03 kg4/15=1.03 4/\sqrt{15} = 1.03 : averaging cancels out the deviations
395 % of the time, ∣Xˉ−μ∣≤2.02 \lvert \bar X – \mu \rvert \le 2.02 Xˉ \bar X is normal and 1.96⋅1.03=2.02 1.96 \cdot 1.03 = 2.02
495 % of the time, μ is between Xˉ−2.02 \bar X – 2.02 and Xˉ+2.02 \bar X + 2.02 the distance from Xˉ \bar X to μ is the same as from μ to Xˉ \bar X
5with 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 (1−α 1 – \alpha with α=0.05 \alpha = 0.05 ) 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, L(X1,…,Xn) L(X_1, \dots, X_n) and U(X1,…,Xn) U(X_1, \dots, X_n) , such that

P(L(X1,…,Xn)≤θ≤U(X1,…,Xn))=1−α P\big(L(X_1,\dots,X_n) \le \theta \le U(X_1,\dots,X_n)\big) = 1 – \alpha

The number 1−α 1 – \alpha is the confidence coefficient and (1−α)⋅100 % (1-\alpha)\cdot 100\,\% the confidence level: with α=0.05 \alpha = 0.05 , 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.

From a number to an intervalTop, the 15 Gáldar bunch weights as dots on an axis from 27 to 47 kilograms, from 28.8 to 45.4. Below, a dashed violet line at the mean 36.88 and, in coral, the 95 percent interval for the mean weight, from 34.86 to 38.90, with two arrows marking the margin of error on each side. The interval is much narrower than the cloud of bunches.28303234363840424446bunch weight (kg)The 15 Gáldar bunches28.8point estimate x̄ = 36.8834.8638.90marginmargin95 % interval for μ
The interval is for the mean weight, not for each bunch: the data cloud is much wider.

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:

estimate±quantile×standard error \text{estimate} \pm \text{quantile} \times \text{standard error}

A good interval does two things at once: P(L≤θ≤U) P(L \le \theta \le U) 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 1−α 1-\alpha : then you ask for P(L≤θ≤U)≥1−α P(L \le \theta \le U) \ge 1-\alpha . 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.

QuestionBefore weighing the bunchesAfter weighing them
What is random?Xˉ \bar X , and with it L and Unothing: you have two numbers
What is fixed?μ (unknown)μ (unknown) and the range (34.86, 38.90)
Which probability makes sense?P(L≤μ≤U)=0.95 P(L \le \mu \le U) = 0.95 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

  • ci is a matrix with 100 rows and 2 columns: each row, the interval of one sample. t() puts it that way because replicate stores each interval in a column.
  • sum(inside) counts the TRUEs: 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.
One hundred 95 % intervalsOne hundred horizontal bars stacked, each the 95 percent interval of a sample of 15 bunches from a normal with mean 38 and standard deviation 4, on an axis from 33 to 43 kilograms. A vertical line marks mu equal to 38. All bars have the same length and shift left and right. Ninety-six cross the line; four, in coral, miss it: samples 35, 66, 68 and 79.3334353637383940414243kgμ = 3896 of 100contain μ4 miss:35, 66, 68, 79sample
The 95 % belongs to the recipe: out of 100 samples, about 95 give an interval that contains μ.

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 20⋅0.9=18 20 \cdot 0.9 = 18 hits. It could come out as 17, 19 or all 20 (all of them being right has probability 0.920=0.12 0.9^{20} = 0.12 ). 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 Q(X1,…,Xn; θ) Q(X_1,\dots,X_n;\,\theta) that:

  1. depends on the sample and on the parameter θ (and on nothing else unknown), and
  2. 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:

The pivot method in four stepsFour boxes in a row joined by arrows. 1, estimator: X bar, the MLE of mu. 2, pivot: Z equals X bar minus mu over sigma over root n, distributed N(0, 1), free of mu. 3, quantiles: minus 1.96 at most Z at most 1.96, leaving alpha over two in each tail. 4, solve: X bar plus or minus 1.96 sigma over root n. Below, a warning: multiplying by minus 1 or taking reciprocals flips the inequalities.1. EstimatorX̄the MLE of μ2. PivotZ = (X̄ − μ)/(σ/√n)N(0, 1): free of μ3. Quantiles−1.96 ≤ Z ≤ 1.96α/2 in each tail4. SolveX̄ ± 1.96 σ/√nμ between L and UIn step 4, multiplying by −1 or taking reciprocals flips the inequalities.
With the mean of a normal and known σ; with any other pivot, the same four steps.
  1. Take a good estimator θ^ \hat\theta of θ (usually the maximum likelihood one).
  2. Find a function of θ and θ^ \hat\theta whose distribution does not depend on θ: the pivot Q.
  3. Find a and b with P(a≤Q≤b)=1−α P(a \le Q \le b) = 1-\alpha , leaving α/2 \alpha/2 in each tail: a is the α/2 \alpha/2 quantile and b the 1−α/2 1-\alpha/2 quantile.
  4. Solve for θ in the double inequality a≤Q≤b a \le Q \le b . 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.

StepWhat you doWith GáldarWhy
1. Estimatoryou choose θ^ \hat\theta Xˉ \bar X , which gave 36.88it is the MLE of μ and its distribution is known
2. Pivotyou mix θ^ \hat\theta and θ into a quantity with a known distributionZ=Xˉ−μσ/n∼N(0,1) Z = \frac{\bar X – \mu}{\sigma/\sqrt n} \sim N(0, 1) subtracting μ centres it at 0 and dividing by σ/n \sigma/\sqrt n leaves it with standard deviation 1: it no longer depends on μ
3. Quantilesyou look for a and b with P(a≤Q≤b)=0.95 P(a \le Q \le b) = 0.95 a = −1.96 and b = 1.962.5 % in each tail: qnorm(0.025) and qnorm(0.975)
4. Solvingyou isolate θ in the middleXˉ±1.96⋅4/15 \bar X \pm 1.96 \cdot 4/\sqrt{15} , 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 Xˉ \bar X on its own not enough? Because its distribution, N(μ,σ/n) N(\mu, \sigma/\sqrt n) , depends on μ, which you do not know: you cannot look up its quantiles. By subtracting μ and dividing by σ/n \sigma/\sqrt n 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 X1,…,Xn X_1, \dots, X_n a simple random sample from N(μ,σ) N(\mu, \sigma) , the estimator of μ is Xˉ \bar X and, as we saw in sampling distributions, Xˉ∼N(μ,σ/n) \bar X \sim N(\mu, \sigma/\sqrt n) .

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

Z=Xˉ−μσ/n∼N(0,1) Z = \frac{\bar X – \mu}{\sigma/\sqrt n} \sim N(0, 1)

and solving for μ in −z1−α/2≤Z≤z1−α/2 -z_{1-\alpha/2} \le Z \le z_{1-\alpha/2} gives

(Xˉ−z1−α/2 σn,  Xˉ+z1−α/2 σn) \left(\bar X – z_{1-\alpha/2}\,\frac{\sigma}{\sqrt n},\ \ \bar X + z_{1-\alpha/2}\,\frac{\sigma}{\sqrt n}\right)

where z1−α/2 z_{1-\alpha/2} is the standard normal quantile that leaves α/2 \alpha/2 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 1.96⋅4/15=1.96⋅1.033=2.02 1.96 \cdot 4/\sqrt{15} = 1.96 \cdot 1.033 = 2.02 .
  • L = 34.86 and U = 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.

StepWhat is leftWhy
0−1.96≤Xˉ−μσ/n≤1.96 -1.96 \le \frac{\bar X – \mu}{\sigma/\sqrt n} \le 1.96 the pivot between its two quantiles, with probability 0.95
1−1.96 σn≤Xˉ−μ≤1.96 σn -1.96\,\frac{\sigma}{\sqrt n} \le \bar X – \mu \le 1.96\,\frac{\sigma}{\sqrt n} multiply by σ/n \sigma/\sqrt n , which is positive: the signs stay the same
2−Xˉ−1.96 σn≤−μ≤−Xˉ+1.96 σn -\bar X – 1.96\,\frac{\sigma}{\sqrt n} \le -\mu \le -\bar X + 1.96\,\frac{\sigma}{\sqrt n} subtract Xˉ \bar X on all three sides, so only μ is left in the middle
3Xˉ+1.96 σn≥μ≥Xˉ−1.96 σn \bar X + 1.96\,\frac{\sigma}{\sqrt n} \ge \mu \ge \bar X – 1.96\,\frac{\sigma}{\sqrt n} multiply by −1: every sign changes and the ≤ \le become ≥ \ge
4Xˉ−1.96 σn≤μ≤Xˉ+1.96 σn \bar X – 1.96\,\frac{\sigma}{\sqrt n} \le \mu \le \bar X + 1.96\,\frac{\sigma}{\sqrt n} 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:

T=Xˉ−μS/n∼t(n−1) T = \frac{\bar X – \mu}{S/\sqrt n} \sim t(n-1)

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:

(Xˉ−tn−1, 1−α/2 Sn,  Xˉ+tn−1, 1−α/2 Sn) \left(\bar X – t_{n-1,\,1-\alpha/2}\,\frac{S}{\sqrt n},\ \ \bar X + t_{n-1,\,1-\alpha/2}\,\frac{S}{\sqrt n}\right)
The normal against the t with 14 degrees of freedomTwo densities over the axis from minus 4 to 4: the standard normal in violet and Student t with 14 degrees of freedom in coral, lower in the center with heavier tails. Dashed lines at plus and minus 1.96 (normal) and plus and minus 2.145 (t). The tails of the t beyond 2.145 are shaded: 2.5 percent on each side.0.00.10.20.30.4−4−3−2−101234z, tdensity1.96−1.962.145−2.145N(0, 1)t(14)2.5 %
To leave 2.5 % in each tail, t(14) needs 2.145 instead of 1.96: the interval widens.

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 Xˉ \bar X . 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σ unknownWhat has changed
PivotZ=Xˉ−μσ/n Z = \frac{\bar X – \mu}{\sigma/\sqrt n} T=Xˉ−μS/n T = \frac{\bar X – \mu}{S/\sqrt n} σ, fixed, becomes S, random
DistributionN(0, 1)t(14)the t pays for the uncertainty in S
Deviation in the marginσ = 4s = 3.888the one from this sample
95 % quantile1.962.145heavier tails, quantile further out
Margin1.96⋅4/15=2.02 1.96 \cdot 4/\sqrt{15} = 2.02 2.145⋅3.888/15=2.15 2.145 \cdot 3.888/\sqrt{15} = 2.15 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 need df = 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: 2.145⋅3.888/15=2.145⋅1.004=2.15 2.145 \cdot 3.888/\sqrt{15} = 2.145 \cdot 1.004 = 2.15 , 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 2.145⋅3/15=2.145⋅0.775=1.66 2.145 \cdot 3/\sqrt{15} = 2.145 \cdot 0.775 = 1.66 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 σ2 \sigma^2 the estimator is S2 S^2 and the pivot is the one from sampling distributions:

Q=(n−1)S2σ2∼χ2(n−1) Q = \frac{(n-1)S^2}{\sigma^2} \sim \chi^2(n-1)

With qα/2 q_{\alpha/2} and q1−α/2 q_{1-\alpha/2} the chi-squared quantiles, P(qα/2≤Q≤q1−α/2)=1−α P(q_{\alpha/2} \le Q \le q_{1-\alpha/2}) = 1-\alpha . When you solve for σ2 \sigma^2 you have to flip the fraction, and the inequality reverses: the big quantile goes to the lower limit.

((n−1)S2q1−α/2,  (n−1)S2qα/2) \left(\frac{(n-1)S^2}{q_{1-\alpha/2}},\ \ \frac{(n-1)S^2}{q_{\alpha/2}}\right)
The chi-squared is not symmetricTop, the chi-squared density with 14 degrees of freedom from 0 to 36, with mean 14 and the two 2.5 percent tails shaded from 5.63 and from 26.12. Bottom, a variance axis from 0 to 40 with the 95 percent interval from 8.10 to 37.60 in coral and the sample variance, 15.12, as a violet dot much closer to the left end.0.000.040.0805101520253035qdensitymean 145.6326.12χ²(14)0510152025303540σ² (kg²)Interval for σ²s² = 15.128.1037.60
Asymmetric quantiles, off-center interval: the σ² interval opens much further upwards.

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 σ2 \sigma^2 is not centred on S2 S^2 .

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 and q_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 σ2 \sigma^2 is (8.10, 37.60) kg². Check: 14⋅15.119=211.67 14 \cdot 15.119 = 211.67 , 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 211.67/5.629=37.60 211.67/5.629 = 37.60 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: σ2 \sigma^2 is in the denominator, so at some point you have to flip the fraction. The rule that controls everything: if two positive numbers satisfy a≤b a \le b , their reciprocals satisfy 1/a≥1/b 1/a \ge 1/b (2 is less than 4, but 1/2 is more than 1/4). With the Gáldar numbers, (n−1)S2=14⋅15.119=211.67 (n-1)S^2 = 14 \cdot 15.119 = 211.67 :

StepWhat is leftWhy
05.629≤211.67σ2≤26.119 5.629 \le \frac{211.67}{\sigma^2} \le 26.119 the pivot between the 0.025 and 0.975 quantiles of χ²(14)
115.629≥σ2211.67≥126.119 \frac{1}{5.629} \ge \frac{\sigma^2}{211.67} \ge \frac{1}{26.119} flip all three sides: they are all positive and the ≤ \le become ≥ \ge
2211.675.629≥σ2≥211.6726.119 \frac{211.67}{5.629} \ge \sigma^2 \ge \frac{211.67}{26.119} multiply by 211.67, which is positive: the signs stay
38.10≤σ2≤37.60 8.10 \le \sigma^2 \le 37.60 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 s2=15.12 s^2 = 15.12 ? 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, 211.67/23.685=8.94 211.67/23.685 = 8.94 , and the small one to the upper limit, 211.67/6.571=32.21 211.67/6.571 = 32.21 . 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 X1,…,Xm X_1,\dots,X_m from N(μ1,σ1) N(\mu_1,\sigma_1) and Y1,…,Yn Y_1,\dots,Y_n from N(μ2,σ2) N(\mu_2,\sigma_2) , independent, the parameter is the difference μ1−μ2 \mu_1 – \mu_2 and the estimator, Xˉ−Yˉ \bar X – \bar Y . 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 σ1 \sigma_1 and σ2 \sigma_2 are known (here 4 and 4.5 kg, from years of weighing), since Xˉ−Yˉ \bar X – \bar Y is normal:

(Xˉ−Yˉ)±z1−α/2σ12m+σ22n (\bar X – \bar Y) \pm z_{1-\alpha/2}\sqrt{\frac{\sigma_1^2}{m} + \frac{\sigma_2^2}{n}}
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 σ1=σ2 \sigma_1 = \sigma_2 without knowing it, you estimate it with the pooled variance, an average of the two variances weighted by their degrees of freedom:

Sp2=(m−1)S12+(n−1)S22m+n−2 S_p^2 = \frac{(m-1)S_1^2 + (n-1)S_2^2}{m+n-2}

and the pivot is a t with m+n−2 m + n – 2 degrees of freedom:

(Xˉ−Yˉ)±tm+n−2, 1−α/2  Sp1m+1n (\bar X – \bar Y) \pm t_{m+n-2,\,1-\alpha/2}\; S_p\sqrt{\frac1m + \frac1n}

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:

Case95 % intervalContains 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 μ1−μ2 \mu_1 – \mu_2 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 Di=Xi−Yi D_i = X_i – Y_i , which are a single sample, and use the t interval for their mean μD \mu_D :

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 σ12/σ22 \sigma_1^2/\sigma_2^2 and the pivot, the F from sampling distributions:

F=S12/σ12S22/σ22∼F(m−1, n−1) F = \frac{S_1^2/\sigma_1^2}{S_2^2/\sigma_2^2} \sim F(m-1,\, n-1)

Solving for the ratio (and flipping the quantiles again):

(S12S22⋅1f1−α/2,  S12S22⋅1fα/2) \left(\frac{S_1^2}{S_2^2}\cdot\frac{1}{f_{1-\alpha/2}},\ \ \frac{S_1^2}{S_2^2}\cdot\frac{1}{f_{\alpha/2}}\right)
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, S12/S22=15.12/28.36=0.53 S_1^2/S_2^2 = 15.12/28.36 = 0.53 , with 14 and 11 degrees of freedom (m−1 m-1 and n−1 n-1 , in that order).
  • p-value and alternative 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 n≥30 n \ge 30 ), the maximum likelihood estimator is approximately normal, with mean θ and a variance that is estimated. The approximate pivot is

θ^−θse^(θ^)≈N(0,1)⟹θ^±z1−α/2 se^(θ^) \frac{\hat\theta – \theta}{\widehat{\mathrm{se}}(\hat\theta)} \approx N(0, 1) \qquad\Longrightarrow\qquad \hat\theta \pm z_{1-\alpha/2}\,\widehat{\mathrm{se}}(\hat\theta)

Only the standard error changes:

PopulationEstimatorStandard errorApproximate interval
Any, mean μXˉ \bar X S/n S/\sqrt n Xˉ±z S/n \bar X \pm z\,S/\sqrt n
Bernoulli(p)p^=Xˉ \hat p = \bar X p^(1−p^)/n \sqrt{\hat p(1-\hat p)/n} p^±zp^(1−p^)/n \hat p \pm z\sqrt{\hat p(1-\hat p)/n}
Poisson(λ)λ^=Xˉ \hat\lambda = \bar X Xˉ/n \sqrt{\bar X/n} Xˉ±zXˉ/n \bar X \pm z\sqrt{\bar X/n}
Exponential(λ)λ^=1/Xˉ \hat\lambda = 1/\bar X λ^/n \hat\lambda/\sqrt n λ^±z λ^/n \hat\lambda \pm z\,\hat\lambda/\sqrt n

One proportion: the rejected bunches

Out of 200 Gáldar bunches, 23 were rejected: p^=23/200=0.115 \hat p = 23/200 = 0.115 . For the normal approximation to be good you need np^≥5 n\hat p \ge 5 and n(1−p^)≥5 n(1-\hat p) \ge 5 : 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 because prop.test uses 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.test is there to compare.

If the data come as zeros and ones (1 = rejected), n is length(x) and p^ \hat p is mean(x). For prop.test you need the number of successes: sum(x).

Two proportions

In Tazacorte 31 out of 180 were rejected (p^2=0.172 \hat p_2 = 0.172 ). For the difference p1−p2 p_1 – p_2 , the standard errors add in squares, as with means:

(p^1−p^2)±z1−α/2p^1(1−p^1)m+p^2(1−p^2)n (\hat p_1 – \hat p_2) \pm z_{1-\alpha/2}\sqrt{\frac{\hat p_1(1-\hat p_1)}{m} + \frac{\hat p_2(1-\hat p_2)}{n}}
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 λ^=1/Xˉ \hat\lambda = 1/\bar X and, by the properties of the MLE, its asymptotic variance is λ2/n \lambda^2/n .

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 λ^=1/26.45=0.0378 \hat\lambda = 1/26.45 = 0.0378 lorries per minute (about 2.3 lorries an hour).
  • The asymptotic one, (0.0261, 0.0495), is symmetric: 0.0378±1.96⋅0.0378/40=0.0378±0.0117 0.0378 \pm 1.96 \cdot 0.0378/\sqrt{40} = 0.0378 \pm 0.0117 .
  • The last line is an exact interval: it comes from 2λ∑Xi∼χ2(2n) 2\lambda\sum X_i \sim \chi^2(2n) , 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, 1/λ 1/\lambda , just invert the ends (the function 1/x 1/x 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 se^=Xˉ/n \widehat{\mathrm{se}} = \sqrt{\bar X/n} , 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 λ^ \hat\lambda , 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 z1−α/2 σ/n z_{1-\alpha/2}\,\sigma/\sqrt n . If we want it not to exceed an amount δ, we just solve for n:

z1−α/2σn≤δ  ⟺  n≥(z1−α/2 σδ)2 z_{1-\alpha/2}\frac{\sigma}{\sqrt n} \le \delta \iff n \ge \left(\frac{z_{1-\alpha/2}\,\sigma}{\delta}\right)^2

If σ is not known, you plug in the S of a pilot sample (or of earlier studies). For a proportion, the margin is zp(1−p)/n z\sqrt{p(1-p)/n} and you get n≥(z/δ)2 p(1−p) n \ge (z/\delta)^2\,p(1-p) . As we do not know p before taking the sample, we use the worst case: p(1−p) p(1-p) never exceeds 1/4, so

n≥(z1−α/22δ)2 n \ge \left(\frac{z_{1-\alpha/2}}{2\delta}\right)^2
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
The margin of error falls with the root of nCurve of the margin of error 1.96 times 4 over root n against the number of bunches, from 5 to 300. A dashed coral line at 1 kilogram cuts it at n equal to 62, and a green one at half a kilogram cuts it at n equal to 246, about four times as many.0123050100150200250300n (bunches)margin (kg)δ = 1 kgδ = 0.5 kgn = 62n = 2461.96 · 4 / √n
For half the margin, four times the data: 62 bunches for 1 kg, 246 for 0.5 kg.
  • To estimate the Gáldar mean weight with an error of at most 1 kg at 95 % (σ = 4): (1.96⋅4/1)2=61.46 (1.96 \cdot 4/1)^2 = 61.46 , 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?

StepWhat is leftWhy
01.96 4n≤1 1.96\,\frac{4}{\sqrt n} \le 1 the margin (quantile times standard error) cannot go over δ = 1
11.96⋅4≤n 1.96 \cdot 4 \le \sqrt n multiply by n \sqrt n , which is positive: the sign stays
27.84≤n 7.84 \le \sqrt n the arithmetic: 1.96 · 4 = 7.84
361.46≤n 61.46 \le n 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)
4n = 62n 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 1.96⋅4/61=1.0038 1.96 \cdot 4/\sqrt{61} = 1.0038 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: p(1−p) p(1-p) 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 n≥(2.576⋅4/0.5)2=424.69 n \ge (2.576 \cdot 4/0.5)^2 = 424.69 (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:

How I choose the intervalA decision tree. At the top, the question: what is the parameter of. Five branches: one mean (if sigma is known, z; otherwise the t with n minus 1 degrees), one variance (chi-squared with n minus 1, quantiles swapped), two means (if paired, the t of the differences; otherwise by sigma1 and sigma2: known, z; equal, the t with m plus n minus 2; unequal, Welch), two variances (the F, before choosing between equal and Welch) and proportions or lambda (with large n, the MLE plus or minus z times its standard error; otherwise the chi-squared with 2n for the exponential or the maximum for the uniform).What is the parameter of?One meanOne varianceTwo meansTwo variancesp, λ, othersσ known?Yes: zqnormNo: t(n − 1)t.test(x)χ²(n − 1)qchisqquantilesswappedPaired?Yes: t of dpaired = TRUENo: σ₁, σ₂?known: zqnormequal: t(m+n−2)var.equal = TRUEunequal: Welcht.test(x, y)F(m − 1, n − 1)var.testbefore choosingequal or WelchLarge n?Yes: MLE ± z·seprop.test, fitdistNo, exponentialχ²(2n)No, uniformX₍ₙ₎/θ
Three questions are almost always enough: which parameter, whether σ is known and whether the samples come in pairs.
If you are asked about…and you know that…PivotIn R
μ of a normalσ knownZqnorm
μ of a normalσ unknownt(n − 1)t.test(x)
σ² or σ of a normal—χ²(n − 1)qchisq, sigma.test
μ₁ − μ₂, normalsσ₁, σ₂ knownZqnorm
μ₁ − μ₂, normalsunknown and equalt(m + n − 2)t.test(x, y, var.equal = TRUE)
μ₁ − μ₂, normalsunknown and unequalWelch’s tt.test(x, y)
μ₁ − μ₂paired datat(n − 1) of the differencest.test(x, y, paired = TRUE)
σ₁²/σ₂², normals—F(m − 1, n − 1)var.test(x, y)
p (or p₁ − p₂)large napproximate Zformula, prop.test
Poisson or exponential λ, any MLElarge napproximate Zformula, fitdist + confint
λ of an exponentialsmall nχ²(2n)qchisq

What is proved in this topic

Each interval has its full derivation in the confidence interval proofs:

ResultIdea of the proof
Interval for μ with known σsolve for μ in −z≤Z≤z -z \le Z \le z
Interval for μ with unknown σT=Z/V/(n−1) T = Z/\sqrt{V/(n-1)} 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 variancessolve inside the F
Exact interval for λ of an exponential∑Xi∼gamma(n,λ) \sum X_i \sim \text{gamma}(n,\lambda) and 2λ∑Xi∼χ2(2n) 2\lambda\sum X_i \sim \chi^2(2n)
Interval for θ of a uniform(0, θ)the pivot X(n)/θ X_{(n)}/\theta has distribution un u^n
Sample sizessolve for n from the margin; p(1−p)≤1/4 p(1-p) \le 1/4

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 is qnorm(0.975): the 5 % is split into two tails. Same with qt, qchisq and qf.
  • 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:

  1. In the Environment tab, ci is a 100 × 2 matrix: one interval per row.
  2. sum(inside) is around 95, even though n is 8: the t corrects for σ being unknown.
  3. In Plots, the bars now have different lengths: with unknown σ, each sample brings its own S.
  4. Change level to 0.80: the bars get shorter and about 20 out of 100 miss.
  5. Replace t.test(x, …)$conf.int with mean(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

IntervalFormulaWith the bananas
μ, known σxˉ±z σ/n \bar x \pm z\,\sigma/\sqrt n (34.86, 38.90) kg
μ, unknown σxˉ±tn−1 s/n \bar x \pm t_{n-1}\,s/\sqrt n (34.73, 39.03) kg
σ²((n−1)s2/q1−α/2, (n−1)s2/qα/2) \big((n-1)s^2/q_{1-\alpha/2},\ (n-1)s^2/q_{\alpha/2}\big) (8.10, 37.60) kg²
μ₁ − μ₂, pooled(xˉ−yˉ)±t sp1/m+1/n (\bar x-\bar y) \pm t\,s_p\sqrt{1/m+1/n} (−0.14, 7.16) kg
Paireddˉ±tn−1 sd/n \bar d \pm t_{n-1}\,s_d/\sqrt n (1.78, 3.78) kg
σ₁²/σ₂² (90 %)(s12s221f1−α/2, s12s221fα/2) \big(\tfrac{s_1^2}{s_2^2}\tfrac{1}{f_{1-\alpha/2}},\ \tfrac{s_1^2}{s_2^2}\tfrac{1}{f_{\alpha/2}}\big) (0.19, 1.37)
pp^±zp^(1−p^)/n \hat p \pm z\sqrt{\hat p(1-\hat p)/n} (0.071, 0.159)
Exponential λλ^±z λ^/n \hat\lambda \pm z\,\hat\lambda/\sqrt n (0.0261, 0.0495)
Size for the meann≥(zσ/δ)2 n \ge (z\sigma/\delta)^2 62 bunches

Three ideas to take away:

  1. 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.
  2. 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.
  3. 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 →