Confidence intervals in R — practice with simulated coverage, the two farms and when the asymptotic one fails

The night before practical 13 I used qnorm(0.975) for the interval of the mean of 5 bunches and I got a range that looked perfect and was not. I had put the sample standard deviation where σ goes, without changing the quantile. It was narrower than my classmate’s, who had used qt, and I thought mine was better because it was narrower. The next day the lecturer made us simulate 10,000 samples and count how many intervals hit: hers, 95 %; mine, 87 %. A narrow interval is useless if it does not deliver the confidence it promises. In this practice we measure exactly that: not just computing intervals, but checking that they hit as often as they claim.

This is the practice for the confidence intervals theory and its proofs. There are three medium-level programs with the cooperative’s bananas: the first measures coverage by simulation (the real 95 %), the second compares the Gáldar and Tazacorte farms from start to finish, plot included, and the third looks for where the asymptotic interval for a proportion fails and works out sample sizes. The data look like real data: an odd bunch on each side, variances you cannot be sure are equal and small proportions, which is where the simple formulas go astray.

Before you start

You should be clear about:

  • What the confidence level means: the percentage of samples in which the method hits.
  • The formulas for the intervals of the mean (with z and with t), of the difference of means and of a proportion.
  • replicate(B, {…}) repeats a block and keeps its results; rowMeans and mean of a logical vector count the proportion of TRUEs.
  • t.test, var.test and prop.test and their $conf.int.

If any of these feels shaky, review the theory before going on.

Simulations with 10,000 repetitions take a few seconds in the website’s R playground. Always put set.seed at the start: that way your numbers will be the same as these and you can compare.

Program 1: coverage, measured

We draw 10,000 samples of 15 bunches from a normal with mean 38 and standard deviation 4 (a “true” mean weight we make up so we can check) and, with each one, compute three 95 % intervals: with z and the true σ, with t and S, and with z and S (the one from my anecdote). We count how often each one hits. Then we repeat the z-with-S one for several sample sizes and plot 50 t intervals.

The idea

An interval hits if ∣xˉ−μ∣≤margin \lvert \bar x – \mu \rvert \le \text{margin} : it is the same condition as L≤μ≤U L \le \mu \le U , written in one line. Each sample produces three TRUEs or FALSEs and the width of the t one; replicate stacks them into a matrix with 4 rows and 10,000 columns and rowMeans gives the hit rate of each method (and the mean width of the t). To see how it changes with n, sapply runs through several sizes.

In plain words: in real life you have a single sample and you don’t know whether your interval hits, because nobody tells you the true mean weight. Here we cheat on purpose: we chose the 38 ourselves, so every interval can be marked. Simulating 10,000 samples is like asking 10,000 classmates to weigh their 15 bunches and compute their interval; if the method keeps its promise, about 9500 of them hit.

Before coding, think about what you expect: with known σ and with t they should come out around 0.95. And with z and S? As the t has heavier tails, the 1.96 quantile is too short: it should hit less, and more so the smaller n is.

The code

set.seed(15)
mu <- 38; sigma <- 4; n <- 15; B <- 10000
z  <- qnorm(0.975)               # 1.96
tq <- qt(0.975, n - 1)           # 2.14: the t(14) one
sims <- replicate(B, {
  x <- rnorm(n, mu, sigma)       # 15 made-up bunches
  m <- mean(x); s <- sd(x)
  c(z_sigma = abs(m - mu) <= z * sigma / sqrt(n),    # right: known sigma
    t_s     = abs(m - mu) <= tq * s / sqrt(n),       # right: unknown sigma
    z_s     = abs(m - mu) <= z * s / sqrt(n),        # wrong: S with the z quantile
    width_t = 2 * tq * s / sqrt(n))                  # length of the t interval
})
round(rowMeans(sims), 4)         # hit rate and mean width

# and with other sizes? The z-with-S one, for several n
coverage_z_s <- sapply(c(5, 10, 15, 30, 60, 120), function(n) {
  mean(replicate(4000, { x <- rnorm(n, mu, sigma); abs(mean(x) - mu) <= z * sd(x) / sqrt(n) }))
})
names(coverage_z_s) <- c(5, 10, 15, 30, 60, 120)
coverage_z_s

# 50 t intervals plotted: the ones that miss, in red
set.seed(16)
ci <- t(replicate(50, t.test(rnorm(n, mu, sigma))$conf.int))
miss <- which(ci[, 1] > mu | ci[, 2] < mu)
miss
plot(NULL, xlim = c(32, 44), ylim = c(1, 50), xlab = "kg", ylab = "sample")
segments(ci[, 1], 1:50, ci[, 2], 1:50, col = ifelse(1:50 %in% miss, "red", "grey40"))
abline(v = mu, lwd = 2)

Output

z_sigma     t_s     z_s width_t 
 0.9509  0.9506  0.9332  4.3471 
      5      10      15      30      60     120 
0.87350 0.91925 0.93225 0.94700 0.94500 0.95025 
[1] 15 25 38
The output plot: 50 t intervalsOutput plot of program 1: fifty horizontal segments, one per sample, over an axis from 32 to 44 kilograms, with a vertical line at 38. The segments have different lengths. Three, in coral, do not cross the line: samples 15, 25 and 38, all three to the right of 38.1102030405032343638404244kgsample
With unknown σ each interval has its own width; 3 out of 50 miss (the coral bars).

How to read it

  • z_sigma = 0.9509 and t_s = 0.9506: the two correct methods hit in 95 % of samples, as they promise.
  • z_s = 0.9332: the one from my anecdote hits in 93.3 %. It promises 95 % and does not deliver.
  • width_t = 4.35 kg: the mean length of the t interval with 15 bunches. Check: 2⋅2.145⋅4/15≈4.43 2 \cdot 2.145 \cdot 4/\sqrt{15} \approx 4.43 ; it comes out a bit less because the mean of S is slightly below σ.
  • coverage_z_s: with 5 values, the “z with S” interval hits only 87 % of the time; with 30, already 94.7 %; with 120, 95 %. The mistake of using z instead of t weighs a lot with small n and vanishes with large n, because t(n − 1) looks more and more like the normal.
  • miss = 15, 25 and 38: of the 50 intervals plotted, 3 miss (6 %, normal with only 50).

In the drawing, each bar is a t interval from one sample and the black line is 38. The bars have different lengths (each sample brings its own S): bar 25 is very short and that is why it misses, even though its center is not far away. The three in coral are the ones in miss.

One sample, from the inside

rowMeans summarises 10,000 columns and doesn’t let you see any of them. Let’s open the fourth, the first one in which the t interval hits and the one from my story misses. With the same seed, replicate(4, …) gives the first four columns of sims (with program 1 already run):

set.seed(15)
samples <- replicate(4, rnorm(15, 38, 4))    # the first 4 samples, one per column
x <- samples[, 4]                            # the fourth: the first one where z with S misses
m <- mean(x); s <- sd(x)
round(c(mean = m, S = s, distance = abs(m - mu)), 2)
round(c(z_sigma = z * sigma / sqrt(n), t_s = tq * s / sqrt(n), z_s = z * s / sqrt(n)), 2)
round(sims[, 4], 2)                          # column 4 of the program's matrix
sum(sims["t_s", ] == 1 & sims["z_s", ] == 0) # samples where t hits and z with S misses

Output:

     mean        S distance 
    39.83     3.54     1.83 
z_sigma     t_s     z_s 
   2.02    1.96    1.79 
z_sigma     t_s     z_s width_t 
   1.00    1.00    0.00    3.92 
[1] 174
MethodMarginDoes it reach 1.83?Why
z with σ1.96⋅4/15=2.02 1.96 \cdot 4/\sqrt{15} = 2.02 Yes: hitsit doesn’t depend on the sample: it’s the same in all 10,000
t with S2.145⋅3.54/15=1.96 2.145 \cdot 3.54/\sqrt{15} = 1.96 Yes, justS came out below 4, but the 2.145 quantile makes up for it
z with S1.96⋅3.54/15=1.79 1.96 \cdot 3.54/\sqrt{15} = 1.79 No: missesthe same low S with the short quantile

Column 4 of sims says the same: 1, 1, 0 and a width of 3.92 (twice the t margin). And since, with the same S, the z margin is always shorter than the t one, it never hits where t misses: the 174 samples at the end are exactly the difference between 0.9506 and 0.9332.

Check you’ve got it: in this sample, how large would S need to be, at least, for the z-with-S interval to hit?

About 3.61. It hits if 1.96⋅S/15≥1.83 1.96 \cdot S/\sqrt{15} \ge 1.83 . Solving, S≥1.83⋅15/1.96≈3.61 S \ge 1.83 \cdot \sqrt{15}/1.96 \approx 3.61 . It came out as 3.54, so it misses. With σ = 4 it does reach: the problem isn’t the 1.96, but using it with an S that sometimes comes out low.

Questions you might ask

Why abs(m - mu) <= margin and not L <= mu & mu <= U? It is the same: xˉ−e≤μ≤xˉ+e \bar x – e \le \mu \le \bar x + e is equivalent to −e≤μ−xˉ≤e -e \le \mu – \bar x \le e , that is, ∣xˉ−μ∣≤e \lvert \bar x – \mu\rvert \le e . In one line and without computing L and U.

Why rowMeans of something with TRUE and FALSE? R turns TRUE into 1 and FALSE into 0 when doing arithmetic, so the mean is the proportion of TRUEs. The width, which is a number, is in the same matrix: rowMeans gives its mean.

Why 0.9509 and not exactly 0.95? Because there are 10,000 samples, not infinitely many. The simulated proportion varies around 0.95 with an error of about 0.95⋅0.05/10000=0.002 \sqrt{0.95\cdot0.05/10000} = 0.002 : any value between 0.946 and 0.954 is to be expected.

Why t() in ci? replicate stores each interval (2 numbers) in a column, and we want one per row so we can use ci[, 1] as L and ci[, 2] as U.

If the 95 % belongs to the method, what is my interval for? For making decisions knowing how often you can be wrong: if you always use 95 % intervals, in the long run you are wrong 1 time in 20.

Checking coverage with a single sample (“my interval contains 38, so it works”). One sample says nothing about a percentage: you need thousands.

Try it yourself

  • Replace the normal with an exponential with mean 38 (rexp(n, 1/38)) and measure the coverage of the t interval with n = 15 and with n = 100. How much does it miss with skewed data?
  • Repeat the first block at 90 % (qnorm(0.95), qt(0.95, n - 1)) and check that the coverage drops to 0.90.

Program 2: the two farms, from start to finish

Do Gáldar bunches weigh more than Tazacorte ones? First we look at them with a boxplot, then we check whether the variances can be equal, we write our own function for the interval of the difference (pooled and Welch) and compare it with t.test, and finally we see what the confidence level does to the range.

The idea

A complete analysis goes in this order: look at the data (anything odd?), choose the case (equal variances?) and compute and interpret. The ci_diff function puts the two formulas from the theory behind an if: with equal = TRUE, the pooled variance and a t with m+n−2 m+n-2 degrees; with FALSE, the Welch standard error and its approximate degrees of freedom.

In plain words: the question isn’t how much a Gáldar bunch weighs, but how much more it weighs, on average, than a Tazacorte one. That’s why we check whether the interval for the difference contains 0: if it’s inside, “no difference” is still believable. The pooled variance is an average of the two sample variances weighted by their degrees of freedom (14 and 11): the farm with more bunches counts more.

Before coding, think about what the function returns: two rounded numbers, L and U. If a function returns the interval, you can call it with several levels and stack the results with rbind.

The code

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)
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)

# 1. Look at the data
b <- boxplot(galdar, tazacorte, names = c("Galdar", "Tazacorte"), ylab = "kg")
b$stats                          # lower whisker, Q1, median, Q3, upper whisker
b$out                            # the outliers

# 2. Our interval for the difference of means
ci_diff <- function(x, y, level = 0.95, equal = TRUE) {
  m <- length(x); n <- length(y); a <- 1 - level
  dif <- mean(x) - mean(y)
  if (equal) {                                       # pooled variance, t(m + n - 2)
    sp2 <- ((m - 1) * var(x) + (n - 1) * var(y)) / (m + n - 2)
    margin <- qt(1 - a / 2, m + n - 2) * sqrt(sp2 * (1 / m + 1 / n))
  } else {                                           # Welch: approximate degrees
    se <- sqrt(var(x) / m + var(y) / n)
    dfs <- se^4 / ((var(x) / m)^2 / (m - 1) + (var(y) / n)^2 / (n - 1))
    margin <- qt(1 - a / 2, dfs) * se
  }
  round(dif + c(-1, 1) * margin, 2)
}

# 3. Equal variances? And the two intervals
round(var.test(galdar, tazacorte)$conf.int, 2)
rbind(pooled = ci_diff(galdar, tazacorte), welch = ci_diff(galdar, tazacorte, equal = FALSE))
round(t.test(galdar, tazacorte, var.equal = TRUE)$conf.int, 2)   # check

# 4. The confidence level
rbind(n90 = ci_diff(galdar, tazacorte, 0.90), n95 = ci_diff(galdar, tazacorte, 0.95),
      n99 = ci_diff(galdar, tazacorte, 0.99))

Output

      [,1]  [,2]
[1,] 32.00 26.10
[2,] 35.10 29.45
[3,] 36.80 31.70
[4,] 38.75 36.45
[5,] 41.20 44.80
[1] 28.8 45.4
[1] 0.16 1.65
attr(,"conf.level")
[1] 0.95
        [,1] [,2]
pooled -0.14 7.16
welch  -0.32 7.35
[1] -0.14  7.16
attr(,"conf.level")
[1] 0.95
     [,1] [,2]
n90  0.49 6.54
n95 -0.14 7.16
n99 -1.43 8.45
The output plot: the two boxplotsOutput plot of program 2: two boxplots over an axis from 24 to 48 kilograms. Gáldar: box from 35.1 to 38.75, median 36.8, whiskers to 32 and 41.2 and two outliers, 28.8 and 45.4. Tazacorte: box from 29.45 to 36.45, taller and wider, median 31.7, whiskers to 26.1 and 44.8, no outliers.24283236404448kg28.845.4Galdar36.8Tazacorte31.7
The medians are apart, but the boxes overlap: the difference is not clear.

How to read it

  • b$stats: each column is a farm. In Gáldar, the median is 36.8 kg and the box goes from 35.1 to 38.75; in Tazacorte, the median is 31.7 and the box, from 29.45 to 36.45, wider. Gáldar’s whiskers stop at 32 and 41.2.
  • b$out = 28.8 and 45.4: two outlying Gáldar bunches, one on each side (look at the drawing: the two loose points). They are more than 1.5 times the interquartile range beyond the box, but they are possible bunch weights, not scale errors: they stay.
  • var.test, (0.16, 1.65) at 95 %: it contains 1, so the variances can be assumed equal. Careful: it is a very wide range; with 15 and 12 bunches you cannot narrow it further.
  • pooled (−0.14, 7.16) and welch (−0.32, 7.35): the ones from the theory, now with our function. The next line, t.test(…, var.equal = TRUE), gives the same: the function is right.
  • The level: at 90 %, (0.49, 6.54), does not contain 0; at 95 % and 99 %, it does. With 90 % confidence Gáldar bunches weigh more; with 95 %, the data fall short. The range widens when you ask for more confidence.

The boxplot shows why the difference is not clear: Gáldar’s median is above Tazacorte’s, but the boxes overlap and Tazacorte’s is taller and wider.

The pooled one, by hand

The output gives (−0.14, 7.16) without showing the working. Here it is:

StepWorkingResultWhy
Center36.88−33.37 36.88 – 33.37 3.51 kghow much more, on average, the Gáldar bunches weigh
Sample variancesvar(galdar), var(tazacorte)15.12 and 28.36Tazacorte varies almost twice as much (its box was wider)
Pooled(14⋅15.12+11⋅28.36)/25 (14 \cdot 15.12 + 11 \cdot 28.36)/25 20.94each variance weighs according to its degrees, m−1=14 m-1 = 14 and n−1=11 n-1 = 11
Standard error20.94 (1/15+1/12) \sqrt{20.94\,(1/15 + 1/12)} 1.77how much the difference moves from one sample to another
Quantileqt(0.975, 25)2.06t with m+n−2=25 m+n-2 = 25 degrees
Interval3.51±2.06⋅1.77=3.51±3.65 3.51 \pm 2.06 \cdot 1.77 = 3.51 \pm 3.65 (−0.14, 7.16)0 is inside by 14 hundredths

What decides the conclusion: the center is positive, but the margin is a little larger than it.

Check you’ve got it: where does the (0.49, 6.54) at 90 % come from?

Same center and same standard error; only the quantile changes: at 90 % there’s 5 % left in each tail, qt(0.95, 25) = 1.71. The margin is 1.71⋅1.77=3.03 1.71 \cdot 1.77 = 3.03 , and 3.51±3.03 3.51 \pm 3.03 gives (0.49, 6.54) with all the decimals. Now the margin is smaller than the center and 0 is left out.

Questions you might ask

What is b <- boxplot(…) for? boxplot draws and also returns the numbers behind the drawing. Saving it in b lets you read b$stats and b$out without computing quartiles by hand.

Why if (equal) inside the function? So as not to write two almost identical functions. The argument with a default value (equal = TRUE) makes the pooled one the normal call.

Where does the dfs formula come from? It is the Welch–Satterthwaite approximation: some degrees of freedom between the smaller of m−1,n−1 m-1, n-1 and m+n−2 m+n-2 . You do not need to know it by heart; it is there so our function gives the same as t.test.

Why does 90 % say yes and 95 % no? Because 0 is close to the lower limit: with the shorter 90 % range it stays out, with the 95 % one it gets in. That is why you must always state the level when you give a conclusion.

Should I remove the outliers? Only if they are errors (a badly calibrated scale, a miscopied value). A 45.4 kg bunch can exist; removing it because it gets in the way is manipulating the data.

Choosing the confidence level after seeing the data (“at 95 % it doesn’t come out, so I’ll give it at 90 %”). The level is decided beforehand. If you change it until you get what you want, 95 % no longer means anything.

Try it yourself

  • Call ci_diff(tazacorte, galdar): what happens to the interval when you swap the order of the samples?
  • Add a paired = FALSE argument to the function that, when TRUE, computes the t interval of x - y, and check it with before and after against t.test(after, before, paired = TRUE).

Program 3: when the asymptotic one fails and how much data you need

The interval for a proportion from the theory (Wald’s, p^±zp^(1−p^)/n \hat p \pm z\sqrt{\hat p(1-\hat p)/n} ) relies on the normal approximation. With the proportion of rejected bunches (around 11.5 %), we measure its coverage with samples of 20 to 320 bunches and compare it with that of prop.test. Then we write the two sample size functions and check what happens if σ is not known.

The idea

For each size n we simulate the number of rejected bunches with rbinom(1, n, p) (a binomial: how many of n bunches are rejected), compute both intervals and check whether they contain 0.115. sapply returns a matrix with one column per n and one row per method, which we plot with plot and lines. For sample size, two one-line functions with ceiling (round up).

In plain words: here coverage depends on n. With 20 bunches, p^ \hat p can only be 0, 1/20, 2/20…, and the normal is a poor imitation of such a stepped binomial. The sample size comes from solving the margin for n: if e=z σ/n e = z\,\sigma/\sqrt n , then n=(z σ/e)2 n = (z\,\sigma/e)^2 .

Before coding, think about where Wald will fail: when np^ n\hat p is small (with n = 20 you expect 2.3 rejected). There the binomial is very skewed and the normal does not mimic it well.

The code

set.seed(17)
p <- 0.115; sizes <- c(20, 40, 80, 160, 320)
cover <- sapply(sizes, function(n) {
  r <- replicate(4000, {
    x  <- rbinom(1, n, p); ph <- x / n                          # rejected out of n bunches
    w  <- ph + c(-1, 1) * qnorm(0.975) * sqrt(ph * (1 - ph) / n) # Wald
    pt <- suppressWarnings(prop.test(x, n)$conf.int)            # Wilson with correction
    c(wald = w[1] <= p & p <= w[2], prop_test = pt[1] <= p & p <= pt[2])
  })
  rowMeans(r)
})
colnames(cover) <- sizes
round(cover, 3)
plot(sizes, cover["wald", ], type = "b", log = "x", ylim = c(0.85, 1),
     xlab = "n", ylab = "coverage")
lines(sizes, cover["prop_test", ], type = "b", col = "blue")
abline(h = 0.95, lty = 2)

# Sample sizes (always round up)
n_mean <- function(sigma, delta, level = 0.95) ceiling((qnorm(1 - (1 - level) / 2) * sigma / delta)^2)
n_prop <- function(delta, p = 0.5, level = 0.95) ceiling((qnorm(1 - (1 - level) / 2) / delta)^2 * p * (1 - p))
c(mean_1kg = n_mean(4, 1), mean_05kg = n_mean(4, 0.5),
  prop_worst = n_prop(0.03), prop_pilot = n_prop(0.03, 0.115))

# And if sigma is unknown? Real margin of 4000 samples of 62 bunches with S and t
set.seed(18)
margin_s <- replicate(4000, { x <- rnorm(62, 38, 4); qt(0.975, 61) * sd(x) / sqrt(62) })
round(c(mean = mean(margin_s), prop_below_1 = mean(margin_s <= 1)), 3)

Output

             20    40    80   160   320
wald      0.905 0.940 0.955 0.948 0.937
prop_test 0.977 0.979 0.969 0.964 0.955
  mean_1kg  mean_05kg prop_worst prop_pilot 
        62        246       1068        435 
        mean prop_below_1 
       1.012        0.450 
The output plot: coverage by nOutput plot of program 3: coverage against the sample size on a log scale, 20, 40, 80, 160 and 320, with a dashed line at 0.95. The coral Wald line starts at 0.905 with 20, rises to 0.940 and 0.955 and then hovers around 0.94 and 0.95. The blue prop.test line is always above: 0.977, 0.979, 0.969, 0.964 and 0.955.0.850.900.951.00ncoverage204080160320Wald (formula)prop.test0.95
Wald falls short with few bunches; prop.test is conservative and over-covers.

How to read it

  • The cover matrix: with 20 bunches, Wald hits 90.5 % of the time (it promises 95 %); prop.test, 97.7 %. With 40, 94 % against 97.9 %; from 80 onwards, Wald is around 95 %.
  • In the drawing, the Wald line (coral) starts below 95 % and rises; the prop.test one (blue) is always above it: it is conservative, it hits more than it promises in exchange for slightly wider ranges. Neither is a smooth line: the binomial is discrete and coverage jumps a bit from one n to the next (which is why Wald drops to 0.937 at 320).
  • mean_1kg = 62 and mean_05kg = 246: half the error, four times the bunches (61.46 × 4 = 245.9 → 246).
  • prop_worst = 1068 and prop_pilot = 435: those from the theory.
  • margin_s: if you work out n = 62 with σ = 4 but then use S and the t, the mean margin comes out at 1.012 and only 45 % of the time it is below 1. The formula guarantees the margin when σ is known; with S it is an approximation, because S changes from one sample to another.

Sample sizes, step by step

The four numbers in the output, unfolded:

CallWorkingBefore roundingWith ceilingWhy
n_mean(4, 1)(1.96⋅4/1)2 (1.96 \cdot 4/1)^2 61.4662with 61 the margin would go over 1 kg
n_mean(4, 0.5)(1.96⋅4/0.5)2 (1.96 \cdot 4/0.5)^2 245.85246half the error doubles the bracket; squared, 4 times more
n_prop(0.03)(1.96/0.03)2⋅0.5⋅0.5 (1.96/0.03)^2 \cdot 0.5 \cdot 0.5 1067.071068with p = 0.5, p(1−p)=0.25 p(1-p) = 0.25 , its maximum
n_prop(0.03, 0.115)(1.96/0.03)2⋅0.115⋅0.885 (1.96/0.03)^2 \cdot 0.115 \cdot 0.885 434.41435with the pilot, p(1−p)≈0.10 p(1-p) \approx 0.10 : about 2.5 times fewer bunches

Questions you might ask

Why rbinom(1, n, p) and not 0s and 1s with rbinom(n, 1, p)? For the proportion only the number rejected matters; generating the total directly is the same and faster.

Why suppressWarnings on prop.test? With small n and few rejected, prop.test warns that the approximation may not be good (“Chi-squared approximation may be incorrect”). We know; the warning, repeated 4000 times, would only get in the way.

Why log = "x" in the plot? The sizes double (20, 40, 80…); on a log scale they are equally spaced and easier to read.

So should I always use prop.test? In the exam, the “asymptotic” interval is the formula one (Wald), checking np^≥5 n\hat p \ge 5 and n(1−p^)≥5 n(1-\hat p) \ge 5 . prop.test is better with small samples; say so if you use it.

Why ceiling and not round? Because 61.46 rounded is 61, and with 61 bunches the margin goes over 1 kg. ceiling always goes up.

Trusting Wald with np^<5 n\hat p < 5 . With 20 bunches and an 11.5 % rejection rate you expect 2.3: the condition fails and the interval hits quite a bit less than it promises.

What would happen if a sample of 20 bunches had no rejected ones at all?

Then p^=0 \hat p = 0 and Wald’s margin is 0: the interval is (0, 0), a single point, and it doesn’t contain 0.115. And it happens with probability 0.88520=0.087 0.885^{20} = 0.087 : for that alone, Wald can no longer reach 95 %. The exact calculation, with the 21 possible results:

xs <- 0:20; ph <- xs / 20                                  # the 21 possible results with 20 bunches
L <- ph - qnorm(0.975) * sqrt(ph * (1 - ph) / 20)          # Wald, lower limit
U <- ph + qnorm(0.975) * sqrt(ph * (1 - ph) / 20)          # Wald, upper limit
hits <- L <= 0.115 & 0.115 <= U                            # does it contain 11.5 %?
round(cbind(x = xs, prob = dbinom(xs, 20, 0.115), L, U, hits)[1:8, ], 3)
round(c(coverage = sum(dbinom(xs, 20, 0.115)[hits]), p_zero = dbinom(0, 20, 0.115)), 3)

Output:

     x  prob      L     U hits
[1,] 0 0.087  0.000 0.000    0
[2,] 1 0.226 -0.046 0.146    1
[3,] 2 0.279 -0.031 0.231    1
[4,] 3 0.217 -0.006 0.306    1
[5,] 4 0.120  0.025 0.375    1
[6,] 5 0.050  0.060 0.440    1
[7,] 6 0.016  0.099 0.501    1
[8,] 7 0.004  0.141 0.559    0
coverage   p_zero 
   0.908    0.087 

With 1 to 6 rejected it hits; with 0 it misses, and with 7 or more (probability 0.005) too. The exact coverage is 0.908; the simulation gave 0.905. With 0 rejected, prop.test gives (0, 0.20), which does contain 0.115: that’s why it holds up where Wald sinks.

Try it yourself

  • Repeat the coverage with p = 0.5 (instead of 0.115). Does Wald fail as much with 20 bunches when the proportion is in the middle?
  • Use n_mean with σ = 3.89 (Gáldar’s S) instead of 4 and an error of 0.5 kg. How many bunches do you save?

Common mistakes in this practice

  • qnorm(0.975) with S and small n. It promises 95 % and hits 93 % with 15 values and 87 % with 5. With unknown σ, qt(0.975, n - 1).
  • Judging a method by a single sample. Coverage is measured with thousands of repetitions and set.seed.
  • Forgetting t() when stacking intervals with replicate. Without it, ci[, 1] is the first interval, not all the lower limits.
  • Choosing the level after seeing the result. 90 % or 95 % is decided beforehand.
  • Wald with very few successes. Check np^≥5 n\hat p \ge 5 and n(1−p^)≥5 n(1-\hat p) \ge 5 before using it.
  • round for the sample size. Always ceiling.

Try it in the R playground

Paste this script into the R playground. It simulates the coverage of the intervals for the variance, which we did not measure in the practice, and plots their asymmetry:

set.seed(21)
n <- 15; sigma2 <- 16; B <- 5000
q <- qchisq(c(0.975, 0.025), n - 1)
ci <- t(replicate(B, (n - 1) * var(rnorm(n, 38, 4)) / q))
mean(ci[, 1] <= sigma2 & sigma2 <= ci[, 2])       # coverage
s2 <- (ci[, 1] * q[1]) / (n - 1)                  # recover each sample's S^2
summary(ci[, 2] - s2); summary(s2 - ci[, 1])      # how far does it open on each side?
hist(s2, breaks = 40, main = "S^2 in 5000 samples", xlab = "kg^2")
abline(v = sigma2, col = "red", lwd = 2)

What to look at:

  1. The coverage is around 0.95.
  2. The two summarys: the range opens much more above than below. It is not symmetric around S2 S^2 .
  3. In Plots, the histogram of S2 S^2 has a long right tail (it is a scaled chi-squared).
  4. Replace rnorm with rexp(n, 1/38) and sigma2 with 38^2: the coverage collapses. The interval for the variance depends heavily on the data being normal.

Summary

  • An interval is worth its coverage: the percentage of samples in which it contains the parameter, which you measure by simulating thousands of samples.
  • With unknown σ, the quantile is the t one: the z one with S falls short, and badly with small n.
  • A two-sample analysis goes in order: look at the data (boxes), decide the case (variances, paired) and compute.
  • The range widens with the confidence level; the level is decided before computing.
  • The Wald interval for a proportion fails with few successes; prop.test is conservative.
  • Sample size is rounded up, and with unknown σ the required margin is only met approximately.

Checklist: have you practised it?

  • Have you run the three programs and checked the outputs?
  • Can you measure the coverage of an interval with replicate and a logical condition?
  • Can you explain why “z with S” hits less than 95 %?
  • Do you know what boxplot returns and how to read b$stats and b$out?
  • Do you know when not to trust the Wald interval?
  • Have you tried the “Try it yourself” tasks without looking at the theory?

If you answered yes to nearly everything, you are ready for the confidence intervals exercises, where I no longer hand you the code. See you there!

Next step: exercisesConfidence intervals — exam-style exercises with bananas, irrigation and breakdowns (and the exact pivot that comes up in EC2)

Did this article help you? Here is how you can support SergioLearns →