Hypothesis Testing

Hypothesis Testing in R: A regional water board is charged with keeping the supply within legal limits, and it cannot possibly test every litre that leaves the…

The Analogy: A Water Board's Sampling Round

A regional water board is charged with keeping the supply within legal limits, and it cannot possibly test every litre that leaves the works. Instead an inspector runs a sampling round: at fixed points across the network they draw a handful of samples, send them to the lab, and read back a number for each determinand -- nitrate, lead, turbidity. The question the board must answer from those few samples is whether the whole supply is within the limit, not just the bottles on the bench.

The difficulty is that samples vary on their own. Two bottles drawn from the same clean main will not read identically; the lab, the time of day, and the exact tap all nudge the number. So a single reading a little above the legal limit is not proof of a breach -- it might be nothing more than the ordinary scatter of sampling. The board needs a rule that separates a real exceedance from routine noise, and that rule is the whole of hypothesis testing.

The rule works by assuming innocence and demanding evidence. The board starts from the position that the supply is compliant -- the true mean sits at or below the limit -- and only abandons that position when the sample is so far above the limit that ordinary scatter is an implausible explanation. It fixes in advance how much doubt it will tolerate: a false-alarm rate, say one wrongly flagged clean supply in twenty. Then it measures how many standard errors the sample mean sits above the limit and asks how often pure chance would produce a sample that extreme. If the answer is smaller than the tolerated rate, the board raises a formal exceedance; if not, it records no cause for concern.

The trap is to read more into the verdict than it carries. A clean round never proves the water pure -- it says only that today's sample gave no strong evidence of a breach, and a small or noisy sample can easily miss a real problem and hand back a false all-clear. The mirror danger is just as real: run the round across a dozen determinands, each at a one-in-twenty alarm rate, and chance alone will eventually flag a determinand that was fine all along. A single flag in a large panel is weak evidence on its own, and a clean pass is never a guarantee. A test measures the strength of evidence against a specific claim; it does not certify safety, and treating it as if it did is how a sampling regime misleads the very public it exists to protect.


Syntax or Core Structure

A hypothesis test in R takes a sample, a null hypothesis, and a tolerated error rate, and returns a test object -- an htest -- carrying a test statistic, its degrees of freedom, and a p-value. The one-sample t-test is the plainest case: is the mean of one sample different from a fixed reference value mu? Here a borehole is sampled nine times and tested against a legal limit of 50 mg/L for nitrate.

nitrate <- c(48, 48, 50, 52, 52, 52, 54, 56, 56)   # mean 52, sd 3
res <- t.test(nitrate, mu = 50)

alpha <- 0.05
writeLines(sprintf("%-10s: %d",   "n", length(nitrate)))
writeLines(sprintf("%-10s: %.2f", "mean", mean(nitrate)))
writeLines(sprintf("%-10s: %.2f", "sd", sd(nitrate)))
writeLines(sprintf("%-10s: %.2f", "limit", 50))
writeLines(sprintf("%-10s: %.4f", "t stat", unname(res$statistic)))
writeLines(sprintf("%-10s: %d",   "df", as.integer(unname(res$parameter))))
writeLines(sprintf("%-10s: %.4f", "p value", res$p.value))
writeLines(sprintf("%-10s: %.2f", "alpha", alpha))
writeLines(sprintf("%-10s: %s",   "reject H0",
                   if (res$p.value < alpha) "TRUE" else "FALSE"))

Output:

n         : 9
mean      : 52.00
sd        : 3.00
limit     : 50.00
t stat    : 2.0000
df        : 8
p value   : 0.0805
alpha     : 0.05
reject H0 : FALSE

The sample mean is 52, two above the limit, and with a standard deviation of 3 across nine samples the standard error is exactly 1, so the t statistic is 2.0 on 8 degrees of freedom. The t statistic counts standard errors from the reference: the mean sits two standard errors above 50. The p-value of 0.0805 is the probability of a sample mean at least this far from 50 in either direction if the true mean really were 50. Because 0.0805 exceeds the tolerated 0.05, the board does not reject the null: the sample runs over the limit, but not by enough to rule out ordinary sampling scatter. That is the crucial reading -- a mean above the limit is not automatically a breach.


Technical Depth: Choosing and Reading a Test

The htest object, and which test answers which question

Every base-R test returns an object of class htest, and it always carries the same named parts: statistic (the test statistic), parameter (degrees of freedom), p.value, and usually conf.int and estimate. You pull them out by name -- res$p.value, unname(res$statistic) -- rather than reading the printed block, which keeps a script from breaking when the print format changes. The hard part is not running a test but picking the one whose null hypothesis matches your question.

QuestionR functionNull hypothesisStatistic
One mean vs a fixed valuet.test(x, mu = k)true mean equals kt
Two independent group meanst.test(x, y)the two means are equalt (Welch)
Paired before/after meanst.test(x, y, paired = TRUE)mean difference is zerot
Association of two numericscor.test(x, y)true correlation is zerot
Counts across categorieschisq.test(tbl)the factors are independentchi-squared
A median without normalitywilcox.test(x, y)the distributions are equalW (rank)

The t-based tests assume roughly normal data; wilcox.test is the rank-based fallback when that assumption is shaky, and chisq.test handles tables of counts rather than measurements. Reaching for the wrong row is the most consequential mistake in this topic, because the p-value is only meaningful relative to the null the test actually posed.

Comparing two independent groups: the Welch t-test

R's t.test(x, y) defaults to the Welch form, which does not assume the two groups share a variance. Its degrees of freedom are therefore usually fractional -- a giveaway that you are running Welch and not the pooled test.

east <- c(49, 51, 52, 52, 53, 55)   # borehole A, n = 6
west <- c(44, 47, 48, 49, 52)       # borehole B, n = 5
res <- t.test(east, west)           # var.equal = FALSE by default

alpha <- 0.05
writeLines(sprintf("%-10s: %d",   "n east", length(east)))
writeLines(sprintf("%-10s: %d",   "n west", length(west)))
writeLines(sprintf("%-10s: %.2f", "mean east", mean(east)))
writeLines(sprintf("%-10s: %.2f", "mean west", mean(west)))
writeLines(sprintf("%-10s: %.4f", "t stat", unname(res$statistic)))
writeLines(sprintf("%-10s: %.4f", "welch df", unname(res$parameter)))
writeLines(sprintf("%-10s: %.4f", "p value", res$p.value))
writeLines(sprintf("%-10s: %s",   "reject H0",
                   if (res$p.value < alpha) "TRUE" else "FALSE"))

Output:

n east    : 6
n west    : 5
mean east : 52.00
mean west : 48.00
t stat    : 2.6001
welch df  : 6.9031
p value   : 0.0359
reject H0 : TRUE

The two boreholes differ by 4 mg/L in the sample, and the Welch test converts that gap into a t of 2.6001 on 6.9031 degrees of freedom. The fractional df is the Welch-Satterthwaite adjustment for unequal variances and unequal sample sizes; it is not a bug. The p-value of 0.0359 is below 0.05, so this time the board rejects the null and concludes the two boreholes genuinely differ. Had the code passed var.equal = TRUE it would have run the pooled t-test with a whole-number df of 9, a different statistic, and a different p-value -- which is why knowing that Welch is the default matters.

Paired measurements: the same units, twice

When each observation is measured twice -- before and after a change at the same site -- the pairs are not independent, and paired = TRUE tells R to test the mean of the within-pair differences against zero. That reduces exactly to a one-sample t-test on the differences.

before <- c(0.30, 0.28, 0.34, 0.31, 0.29, 0.33)
after  <- c(0.32, 0.31, 0.33, 0.35, 0.29, 0.31)
res <- t.test(after, before, paired = TRUE)

alpha <- 0.05
diffs <- after - before
writeLines(sprintf("%-12s: %d",   "pairs", length(diffs)))
writeLines(sprintf("%-12s: %.4f", "mean diff", mean(diffs)))
writeLines(sprintf("%-12s: %.4f", "sd diff", sd(diffs)))
writeLines(sprintf("%-12s: %.4f", "t stat", unname(res$statistic)))
writeLines(sprintf("%-12s: %d",   "df", as.integer(unname(res$parameter))))
writeLines(sprintf("%-12s: %.4f", "p value", res$p.value))
writeLines(sprintf("%-12s: %s",   "reject H0",
                   if (res$p.value < alpha) "TRUE" else "FALSE"))

Output:

pairs       : 6
mean diff   : 0.0100
sd diff     : 0.0237
t stat      : 1.0351
df          : 5
p value     : 0.3481
reject H0   : FALSE

The dosing change raised the residual by 0.01 mg/L on average, but the site-to-site differences scatter by more than twice that, so the t statistic is only 1.0351 on 5 degrees of freedom and the p-value is 0.3481. The board cannot conclude the change did anything. Note what the pairing bought: by comparing each site to itself, the test cancels the large differences between sites and looks only at the change, which is far more sensitive than treating the twelve numbers as two independent groups.

Testing an association: cor.test

cor.test asks whether two numeric variables move together. Its null is that the true correlation is zero, and it converts the sample correlation r into a t statistic on n minus 2 degrees of freedom.

dose     <- c(2, 4, 6, 8, 10, 12)
residual <- c(5, 6, 9, 8, 12, 13)
res <- cor.test(dose, residual)

alpha <- 0.05
writeLines(sprintf("%-10s: %d",   "n", length(dose)))
writeLines(sprintf("%-10s: %.4f", "pearson r", unname(res$estimate)))
writeLines(sprintf("%-10s: %.4f", "t stat", unname(res$statistic)))
writeLines(sprintf("%-10s: %d",   "df", as.integer(unname(res$parameter))))
writeLines(sprintf("%-10s: %.4f", "p value", res$p.value))
writeLines(sprintf("%-10s: %s",   "reject H0",
                   if (res$p.value < alpha) "TRUE" else "FALSE"))

Output:

n         : 6
pearson r : 0.9555
t stat    : 6.4817
df        : 4
p value   : 0.0029
reject H0 : TRUE

The sample correlation is 0.9555, a strong positive association, and on 4 degrees of freedom that gives a t of 6.4817 and a p-value of 0.0029 -- comfortably below 0.05, so the board rejects the null of no association. Two cautions ride along with this result. A correlation is not a cause: dose and residual moving together does not prove one drives the other. And with only six points a single outlier could swing r hard, so a significant correlation on a small sample should always be looked at alongside a scatter plot, never trusted from the number alone.


Real World Example: A Quarterly Compliance Sweep

At the end of a quarter the board tests three determinands against their legal limits, each from eight samples, and prints a compliance table. A determinand is flagged only if its mean is above the limit and the one-sample t-test rejects the null at the 5 percent level -- both conditions, so a mean below the limit is never flagged however significant the test.

sweep <- list(
  Nitrate   = list(limit = 50, x = c(47, 49, 50, 52, 53, 51, 48, 50)),
  Lead      = list(limit = 10, x = c(9, 12, 13, 11, 14, 12, 14, 11)),
  Turbidity = list(limit = 1,  x = c(0.62, 0.80, 1.20, 0.94, 0.70, 1.06, 0.78, 0.86))
)
alpha <- 0.05

writeLines(sprintf("%-10s%4s%8s%8s%9s%8s%6s",
                   "DETERMIN", "N", "MEAN", "LIMIT", "T", "P", "FLAG"))
writeLines(strrep("-", 53))
for (name in names(sweep)) {
  d <- sweep[[name]]
  res <- t.test(d$x, mu = d$limit)
  m <- mean(d$x)
  flag <- if (res$p.value < alpha && m > d$limit) "YES" else "no"
  writeLines(sprintf("%-10s%4d%8.2f%8.2f%9.3f%8.4f%6s",
                     name, length(d$x), m, d$limit,
                     unname(res$statistic), res$p.value, flag))
}
writeLines(strrep("-", 53))
writeLines("")

k <- length(sweep)
flags <- sum(sapply(names(sweep), function(name) {
  d <- sweep[[name]]; res <- t.test(d$x, mu = d$limit)
  res$p.value < alpha && mean(d$x) > d$limit
}))
fwer <- 1 - (1 - alpha)^k
writeLines(sprintf("%-22s: %d",   "determinands tested", k))
writeLines(sprintf("%-22s: %d",   "flagged", flags))
writeLines(sprintf("%-22s: %.2f", "alpha per test", alpha))
writeLines(sprintf("%-22s: %.4f", "family-wise alarm", fwer))

Output:

DETERMIN     N    MEAN   LIMIT        T       P  FLAG
-----------------------------------------------------
Nitrate      8   50.00   50.00    0.000  1.0000    no
Lead         8   12.00   10.00    3.347  0.0123   YES
Turbidity    8    0.87    1.00   -1.929  0.0951    no
-----------------------------------------------------

determinands tested   : 3
flagged               : 1
alpha per test        : 0.05
family-wise alarm     : 0.1426

The table reads cleanly determinand by determinand. Nitrate averages exactly on its limit, so its t statistic is 0 and its p-value is 1 -- no evidence whatever of an exceedance. Lead averages 12 against a limit of 10, and with a t of 3.347 on 7 degrees of freedom its p-value of 0.0123 is well below 0.05, so it is flagged. Turbidity averages 0.87 below its limit of 1.0; its test is nearly significant at p equals 0.0951, but because the mean is under the limit the flag rule correctly withholds a violation. Each row, on its own, is a defensible piece of statistics.

The number that should stop the reader is the last one. Three determinands were each tested at a 5 percent false-alarm rate, and 5 percent per test does not mean 5 percent overall. If all three supplies were in truth perfectly compliant, the chance that at least one test fires by pure luck is one minus 0.95 cubed, which is 0.1426 -- nearly three times the per-test rate. Run a realistic panel of a dozen determinands and that family-wise alarm rate climbs past one in two. The flag on Lead here is almost certainly real, given how far its mean sits above the limit, but in a large sweep a lone flag is exactly what chance produces, and reading it as proof would raise a false alarm.

This is the analogy's fourth paragraph made concrete: a big enough round will flag something clean sooner or later. The honest fix is to control for multiple testing -- a Bonferroni threshold divides alpha by the number of tests, and p.adjust implements the standard corrections -- so that the panel as a whole keeps a 5 percent alarm rate rather than each test keeping its own. This code does none of that, and that is its first and most serious flaw: it reports three independent 5 percent tests and a family-wise rate side by side without ever applying the correction the family-wise rate demands.

Three narrower weaknesses sit alongside it. The test is two-sided, testing whether the mean differs from the limit in either direction, when the board only cares about exceedance -- a one-sided alternative = "greater" would match the real question and roughly halve the p-value, changing which determinands flag. The whole scheme tests the mean against the limit, yet many regulations are written on a percentile or a single-sample maximum, so a supply that breaches on one bad sample can pass a test of the mean. And with only eight samples the t-test leans on an assumption of roughly normal data that eight points cannot really confirm; a rank-based wilcox.test would be the safer instrument when that assumption is in doubt.


Common Mistakes

  1. Reading a non-significant result as proof of no effect. Failing to reject the null means the sample did not show strong enough evidence, not that the effect is zero. A small or noisy sample routinely fails to reject a real effect; "not significant" and "no difference" are different statements, and conflating them is the most common error in applied testing.
  1. Treating a small p-value as a big or important effect. The p-value measures evidence against the null, not the size of the effect. With a large enough sample a trivial, meaningless difference becomes highly significant. Always report the effect size or a confidence interval next to the p-value, so significance is not mistaken for magnitude.
  1. Running many tests and celebrating the one that fires. Each test at 5 percent carries a 5 percent false-alarm rate, so a panel of twenty will on average produce one significant result from pure chance. Correct for multiple comparisons with p.adjust or a Bonferroni threshold before trusting a lone flag in a large family of tests.
  1. Using an unpaired test on paired data. When the same units are measured twice, t.test(x, y) throws away the pairing and is far less sensitive than t.test(x, y, paired = TRUE). The pairing cancels the between-unit variation; ignoring it can hide a real effect behind noise that the paired test would have removed.
  1. Assuming t.test(x, y) pools the variance. R's default is the Welch test, which does not assume equal variances and reports fractional degrees of freedom. If you specifically want the pooled Student test you must pass var.equal = TRUE; assuming the default did so will misread the df and the statistic.
  1. Choosing the test after seeing the result, or the direction after seeing the data. Deciding to run a one-sided test, or picking the alternative direction, once you have glimpsed which way the data points inflates the false-alarm rate. The hypothesis and its direction must be fixed before the data is examined, exactly as the board fixes the limit before sampling.
  1. Ignoring the test's assumptions. A t-test assumes roughly normal data and independent observations; a chi-squared test needs adequate expected counts in each cell. Running the test regardless of whether those hold produces a p-value that looks precise but means nothing. Check the assumptions, or use a rank-based alternative such as wilcox.test.
  1. Confusing correlation with causation. A significant cor.test says two variables move together, not that one causes the other. A lurking third variable can drive both. The p-value speaks only to whether the association is distinguishable from zero, never to why the association exists.
  1. Testing the mean when the rule is about something else. Many limits are written on a maximum, a percentile, or a single-sample threshold, not on the average. A supply can pass a test of the mean while breaching on individual samples. Test the quantity the rule actually governs, not whichever statistic is easiest to compute.

Best Practices

  • State the null hypothesis, the tolerated error rate, and the direction of the test before you touch the data, so the result cannot be shaped by what you hope to find.
  • Report an effect size or confidence interval beside every p-value. res$conf.int and res$estimate carry the magnitude the p-value alone omits, and the interval says how precisely the effect is pinned down.
  • Pull results out of the htest object by name -- res$p.value, unname(res$statistic), res$conf.int -- rather than parsing the printed block, so the code survives a change in print format.
  • Match the test to the design: paired = TRUE for repeated measures on the same units, the Welch default for independent groups, cor.test for association, chisq.test for counts.
  • Correct for multiple comparisons with p.adjust whenever you run a family of tests, so the whole panel keeps its intended error rate instead of each test keeping its own.
  • Check the assumptions before trusting the p-value, and fall back to a rank-based test such as wilcox.test when normality is doubtful or the sample is small.
  • Prefer a one-sided alternative only when the question is genuinely one-directional and that direction was fixed in advance, and say so explicitly, because it halves the p-value relative to the two-sided test.
  • Set the seed before any test that uses simulation or resampling (chisq.test(..., simulate.p.value = TRUE), bootstraps), so the reported p-value is reproducible rather than shifting run to run.

Practice Exercises

  1. A one-sample t.test on twelve readings against a limit of 8 returns a p-value of 0.2 and a sample mean of 8.6. Write down, in plain language, exactly what that p-value means and what it does not mean, and state whether the board should conclude the supply is compliant. Explain your reasoning in terms of evidence rather than proof.
  1. You have before-and-after readings at ten sites following a treatment change. Write both the wrong call, t.test(after, before), and the right call, t.test(after, before, paired = TRUE), and explain which between-site variation the paired test removes and why that makes it more sensitive to a real change.
  1. A colleague runs eighteen independent t-tests, each at alpha equals 0.05, and reports the one that came back significant as a discovery. Compute the probability that at least one of eighteen truly-null tests fires by chance, and write the p.adjust call that would control the family-wise error rate across all eighteen.
  1. Given res <- t.test(x, mu = 100), write the lines that extract the t statistic, the degrees of freedom, the p-value, and the 95 percent confidence interval from the object by name, and explain how you would decide from the confidence interval alone whether the test rejects at the 5 percent level.