11.2 Comparisons: tests

DATA 412/612 · Week 11 · PDF · Source (.qmd)

A project that fits a model of a numeric outcome starts in 11.1 A path for a new dataset. Use this note when the question is a comparison: one mean, two means, three or more means, a proportion, or a table of counts. Each test is explained first. Its examples, and their code, come immediately after that explanation. The one-page menu is at the end. The nested anova() at the end of section 2 is the same comparison the project path uses when you add one predictor.

1. What to do when you have a hypothesis

A hypothesis is a claim you can check with data. The function call is late in the work.

  1. Write the claim in one sentence, and write the “no difference” version of that sentence. The second sentence is H0.
  2. Name the outcome and the grouping, or the second variable. Say whether the outcome is a mean, a proportion, a count in a table, or an association between two numbers.
  3. Plot that relationship. A test on a picture you have not looked at is easy to misread.
  4. Pick the test from section 2. The shape of the question picks the function.
  5. Save the test as an object. Printing it once is not enough if you later want the p-value or the interval.
  6. Report three things: the estimate, a confidence interval, and the p-value.
  7. Write a sentence a reader can use. The sentence names the groups, the direction, and the size, and then mentions the p-value as evidence against H0.

Example of step 1, still before any code. Claim: manual cars get higher miles per gallon than automatic cars. H0: mean mpg is the same for the two transmission codes. That H0 is a two-group mean, so the test is a two-sample t.test(). The code is in that part of section 2.


2. Which test to use

Choose from the question, not from a favorite function. Under each test, the explanation comes first and the two examples follow. Sleuth3 is optional. Install it once in the console if you want the classic tables. The examples run without it.

library(tidyverse)
library(palmerpenguins)
install.packages("Sleuth3")
data("case0201", package = "Sleuth3")

case0201 is wide: Cross and Self are two numeric columns. t.test(Cross, Self) is the two-vector form. The formula form needs a long table.

A t-test is about a mean. There are three of them, and the pairing of the rows decides which one.

  • One-sample t-test. Compare the mean of a single group with a known or hypothesized value. Example: is the average height of plants in one field different from a standard 1.5 m?
  • Independent (two-sample) t-test. Compare the means of two separate, unrelated groups. Example: plants in Field A versus different plants in Field B.
  • Paired (dependent) t-test. Compare two means from the same units at different times or under different conditions. Example: the same plants measured before and after fertilizer.

The plant numbers below are a small teaching table, written out so the shape of each test is visible. The later examples use mtcars, penguins, iris, sleep, and shoes. If the population standard deviation is already known, the mean test is a z-test, covered after the paired examples.

Student’s t-test (Bozeman Science) walks through these three t-tests. Hypothesis testing: z tests and t tests, one- and two-tailed (Organic Chemistry Tutor) is the comparison with a z-test, including one-sided alternatives.

One-sample t-test

Use a one-sample t-test when there is one numeric column and the claim names a specific mean. H0: the mean equals that number. The call is t.test(x, mu = 1.5). The number in mu has to come from the hypothesis, not from the sample mean you just computed. “Is mean height equal to 1.5 m?” is this test. “Is mean height different in Field A and Field B?” is the next one.

Example 1. Eight plants in one field. The standard height, named in advance, is 1.5 m. H0: mean height is 1.5.

plants <- c(1.42, 1.55, 1.61, 1.38, 1.70, 1.49, 1.58, 1.46)
t.test(plants, mu = 1.5)
## 
##  One Sample t-test
## 
## data:  plants
## t = 0.63238, df = 7, p-value = 0.5472
## alternative hypothesis: true mean is not equal to 1.5
## 95 percent confidence interval:
##  1.434943 1.612557
## sample estimates:
## mean of x 
##   1.52375

The mean is about 1.52 m. The interval covers 1.5, and the p-value is about 0.55, so these plants are a weak case against the standard height.

Example 2. mtcars has one column of miles per gallon. The claim names 20 in advance. H0: mean mpg is 20.

tt_one <- t.test(mtcars$mpg, mu = 20)
tt_one
## 
##  One Sample t-test
## 
## data:  mtcars$mpg
## t = 0.08506, df = 31, p-value = 0.9328
## alternative hypothesis: true mean is not equal to 20
## 95 percent confidence interval:
##  17.91768 22.26357
## sample estimates:
## mean of x 
##  20.09062

The p-value is about 0.93. The mean of mpg is compatible with 20, so these data are a weak case against H0.

Example 3. iris has one column of sepal length, in centimeters. The claim names 5.8 cm in advance. H0: mean Sepal.Length is 5.8.

tt_iris <- t.test(iris$Sepal.Length, mu = 5.8)
tt_iris
## 
##  One Sample t-test
## 
## data:  iris$Sepal.Length
## t = 0.64092, df = 149, p-value = 0.5226
## alternative hypothesis: true mean is not equal to 5.8
## 95 percent confidence interval:
##  5.709732 5.976934
## sample estimates:
## mean of x 
##  5.843333

Independent (two-sample) t-test

Use an independent t-test when the outcome is numeric and the grouping variable has exactly two levels, and the rows in the two groups are different units. H0: the two means are equal. The call is t.test(y ~ group). The default is Welch. It does not assume the two groups have the same variance. That is the usual choice. species in penguins has three levels, so this test is legal only after you filter to the pair the hypothesis names and call droplevels(). Three or more groups belong to aov(), below.

Example 1. Field A and Field B hold different plants. H0: mean height is the same in the two fields.

fields <- tibble(
  field = rep(c("A", "B"), each = 6),
  height = c(
    1.40, 1.52, 1.47, 1.55, 1.43, 1.50,
    1.72, 1.68, 1.80, 1.75, 1.66, 1.78
  )
)

t.test(height ~ field, data = fields)
## 
##  Welch Two Sample t-test
## 
## data:  height by field
## t = -7.8597, df = 9.9963, p-value = 1.377e-05
## alternative hypothesis: true difference in means between group A and group B is not equal to 0
## 95 percent confidence interval:
##  -0.3251539 -0.1815128
## sample estimates:
## mean in group A mean in group B 
##        1.478333        1.731667

Field A averages about 1.48 m and Field B about 1.73 m. The p-value is very small, so these data are evidence against equal means.

Example 2. Automatic and manual cars are different cars. The outcome is mpg, and am has two codes. H0: mean mpg is the same for the two transmission codes. Plot first.

ggplot(mtcars, aes(x = factor(am), y = mpg)) +
  geom_boxplot() +
  theme_bw()

tt <- t.test(mpg ~ factor(am), data = mtcars)
tt
## 
##  Welch Two Sample t-test
## 
## data:  mpg by factor(am)
## t = -3.7671, df = 18.332, p-value = 0.001374
## alternative hypothesis: true difference in means between group 0 and group 1 is not equal to 0
## 95 percent confidence interval:
##  -11.280194  -3.209684
## sample estimates:
## mean in group 0 mean in group 1 
##        17.14737        24.39231

Example 3. Adelie and Gentoo are two species. species also contains Chinstrap, so filter to the pair the hypothesis names and drop the unused level. H0: mean bill length is the same for Adelie and Gentoo.

penguins2 <- penguins |>
  filter(species %in% c("Adelie", "Gentoo")) |>
  droplevels()

ggplot(penguins2, aes(x = species, y = bill_length_mm)) +
  geom_boxplot() +
  theme_bw()

tt_bill <- t.test(bill_length_mm ~ species, data = penguins2)
tt_bill
## 
##  Welch Two Sample t-test
## 
## data:  bill_length_mm by species
## t = -24.725, df = 242.58, p-value < 2.2e-16
## alternative hypothesis: true difference in means between group Adelie and group Gentoo is not equal to 0
## 95 percent confidence interval:
##  -9.407672 -8.019303
## sample estimates:
## mean in group Adelie mean in group Gentoo 
##             38.79139             47.50488

case0201 in Sleuth3, after a pivot, is this same two-sample pattern. The chunk runs when the package is installed.

if (requireNamespace("Sleuth3", quietly = TRUE)) {
  data("case0201", package = "Sleuth3")
  case0201 |>
    pivot_longer(everything(), names_to = "type", values_to = "height") |>
    t.test(height ~ type, data = _)
}

Paired (dependent) t-test

Use a paired t-test when each unit contributes two numbers, such as the same plants before and after fertilizer, or the same subject under two drugs. H0: the mean change is zero. The call is t.test(before, after, paired = TRUE). The pairing is the point. Dropping it treats the two columns as two unrelated groups and answers a different question. Pass the two measurements as two vectors. The formula form of t.test() does not accept paired.

Example 1. The same six plants are measured before fertilizer and again after. H0: the mean change in height is zero.

fert <- tibble(
  before = c(1.40, 1.52, 1.47, 1.55, 1.43, 1.50),
  after = c(1.58, 1.66, 1.61, 1.74, 1.57, 1.69)
)

t.test(fert$before, fert$after, paired = TRUE)
## 
##  Paired t-test
## 
## data:  fert$before and fert$after
## t = -15.495, df = 5, p-value = 2.033e-05
## alternative hypothesis: true mean difference is not equal to 0
## 95 percent confidence interval:
##  -0.1904296 -0.1362370
## sample estimates:
## mean difference 
##      -0.1633333

The mean of before minus after is about −0.16 m, so these plants are taller after fertilizer. The p-value is very small.

Example 2. sleep records extra hours of sleep for the same 10 people under two drugs. Each person contributes two numbers. H0: the mean change in extra sleep is zero.

tt_sleep <- t.test(
  sleep$extra[sleep$group == 1],
  sleep$extra[sleep$group == 2],
  paired = TRUE
)
tt_sleep
## 
##  Paired t-test
## 
## data:  sleep$extra[sleep$group == 1] and sleep$extra[sleep$group == 2]
## t = -4.0621, df = 9, p-value = 0.002833
## alternative hypothesis: true mean difference is not equal to 0
## 95 percent confidence interval:
##  -2.4598858 -0.7001142
## sample estimates:
## mean difference 
##           -1.58

Example 3. shoes in the MASS package records sole wear for materials A and B on the same 10 boys. H0: the mean difference in wear is zero.

tt_shoes <- t.test(MASS::shoes$A, MASS::shoes$B, paired = TRUE)
tt_shoes
## 
##  Paired t-test
## 
## data:  MASS::shoes$A and MASS::shoes$B
## t = -3.3489, df = 9, p-value = 0.008539
## alternative hypothesis: true mean difference is not equal to 0
## 95 percent confidence interval:
##  -0.6869539 -0.1330461
## sample estimates:
## mean difference 
##           -0.41

A z-test

A z-test for a mean uses the standard normal curve. It is the right test when the population standard deviation, σ, is known rather than estimated from the sample. For one group,

z = (sample mean − μ0) / (σ / √n)

A t-test is that same comparison when σ is unknown. t.test() puts the sample standard deviation in the denominator and uses a t distribution with n − 1 degrees of freedom. That is the call in the plant, mtcars, and sleep examples above. Use a z-test because σ is known, not because a p-value would look smaller.

For a large sample the t curve sits close to the normal curve, so the two p-values nearly agree. The choice is still whether σ is known.

A claim about a proportion, when the sample is large, is also read off a normal approximation. For one proportion, the chi-square statistic printed by prop.test() is the square of that z statistic. Plant height is not a proportion, so those eight numbers stay a t-test unless σ is given.

One-sided or two-sided. H0 does not change. The alternative does. The default in t.test() is two-sided: the mean differs from the claimed value, in either direction. If the hypothesis you wrote first says the mean is larger, or smaller, set alternative = "greater" or alternative = "less". Choose that direction before you look at the data.

Example. The same eight plants, and H0 is still mean height is 1.5 m. This time the population standard deviation is known to be 0.10 m, so the test is a z-test. The two-sided p-value is the normal probability of a z at least this far from zero.

plants <- c(1.42, 1.55, 1.61, 1.38, 1.70, 1.49, 1.58, 1.46)
sigma <- 0.10
z <- (mean(plants) - 1.5) / (sigma / sqrt(length(plants)))
z
## [1] 0.6717514
2 * pnorm(-abs(z))
## [1] 0.5017419

z is about 0.67 and the two-sided p-value is about 0.50. The t-test on the same plants, which estimated the standard deviation, had a p-value of about 0.55. Same conclusion: these plants are a weak case against a mean of 1.5 m.

Three or more group means

Use aov() when the outcome is numeric and the factor has three or more levels. H0: all of the means are equal. The call is aov(y ~ group), then summary(). A small p-value is evidence that the means are not all equal. It does not name which group differs from which. Running a two-sample t-test on every pair, then keeping the smallest p-value, is a different procedure and makes those p-values mean something else.

Example 1. Bill length for Adelie, Chinstrap, and Gentoo. Three means, one factor. H0: mean bill length is the same for all three species. A small p-value says the means are not all equal. It does not say which species differs from which.

fit_aov <- aov(bill_length_mm ~ species, data = penguins)
summary(fit_aov)
##              Df Sum Sq Mean Sq F value Pr(>F)    
## species       2   7194    3597   410.6 <2e-16 ***
## Residuals   339   2970       9                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 2 observations deleted due to missingness

Example 2. Sepal length for setosa, versicolor, and virginica. H0: mean Sepal.Length is the same for all three iris species.

fit_iris <- aov(Sepal.Length ~ Species, data = iris)
summary(fit_iris)
##              Df Sum Sq Mean Sq F value Pr(>F)    
## Species       2  63.21  31.606   119.3 <2e-16 ***
## Residuals   147  38.96   0.265                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

ANOVA using R (R Programming 101) and ANOVA in R: aov() (Dr. Kidd) run this same aov() summary.

Two numeric variables moving together

Use cor.test() when both columns are numeric and the claim is that they rise and fall together. There is no grouping variable. H0: the correlation is zero. The call is cor.test(x, y). “Heavier cars get fewer miles per gallon” is this test. “Manual cars get more miles per gallon than automatic cars” is a two-sample t-test, because am is a group.

Example 1. Weight and miles per gallon are both numbers. There is no grouping variable. H0: wt and mpg are uncorrelated.

ct <- cor.test(mtcars$wt, mtcars$mpg)
ct
## 
##  Pearson's product-moment correlation
## 
## data:  mtcars$wt and mtcars$mpg
## t = -9.559, df = 30, p-value = 1.294e-10
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  -0.9338264 -0.7440872
## sample estimates:
##        cor 
## -0.8676594

Example 2. Bill length and flipper length are both measurements on the same penguin. Drop birds with a missing value. H0: bill length and flipper length are uncorrelated.

peng_meas <- penguins |>
  filter(!is.na(bill_length_mm), !is.na(flipper_length_mm))

ct_peng <- cor.test(peng_meas$bill_length_mm, peng_meas$flipper_length_mm)
ct_peng
## 
##  Pearson's product-moment correlation
## 
## data:  peng_meas$bill_length_mm and peng_meas$flipper_length_mm
## t = 16.034, df = 340, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  0.5912769 0.7126403
## sample estimates:
##       cor 
## 0.6561813

A proportion

Use prop.test() when the data are counts of successes and a sample size, and the claim is about a proportion. H0: the proportion equals the guess, or the two proportions are equal. The call is prop.test(x = successes, n = n, p = 0.5). A t-test needs the raw numeric outcome. A proportion test needs the count and the sample size.

Example 1. One proportion. Count how many cars have a straight engine (vs == 1), and divide by the number of cars. H0: that proportion is 1/2.

prop.test(
  x = sum(mtcars$vs == 1),
  n = nrow(mtcars),
  p = 0.5
)
## 
##  1-sample proportions test with continuity correction
## 
## data:  sum(mtcars$vs == 1) out of nrow(mtcars), null probability 0.5
## X-squared = 0.28125, df = 1, p-value = 0.5959
## alternative hypothesis: true p is not equal to 0.5
## 95 percent confidence interval:
##  0.2683511 0.6211967
## sample estimates:
##      p 
## 0.4375

The sample proportion is about 0.44, and the interval covers 0.5. The p-value is about 0.60, so these data are a weak case against that H0.

Example 2. Two proportions. Separate the same count by transmission code: straight engines among automatic cars, and straight engines among manual cars. H0: the two proportions are equal.

prop.test(
  x = c(
    sum(mtcars$am == 0 & mtcars$vs == 1),
    sum(mtcars$am == 1 & mtcars$vs == 1)
  ),
  n = c(sum(mtcars$am == 0), sum(mtcars$am == 1))
)
## 
##  2-sample test for equality of proportions with continuity correction
## 
## data:  c(sum(mtcars$am == 0 & mtcars$vs == 1), sum(mtcars$am == 1 & mtcars$vs == 1)) out of c(sum(mtcars$am == 0), sum(mtcars$am == 1))
## X-squared = 0.34754, df = 1, p-value = 0.5555
## alternative hypothesis: two.sided
## 95 percent confidence interval:
##  -0.5819233  0.2418423
## sample estimates:
##    prop 1    prop 2 
## 0.3684211 0.5384615

Two categorical variables

Use chisq.test() when both variables are categories and you have a table of counts. H0: the two factors are independent. The call is chisq.test(table(a, b)). “Is transmission code related to engine shape?” is this test. The cells are counts of cars, not measurements of miles per gallon, so a t-test does not apply.

Example 1. Transmission code and engine shape are both categories. The table holds counts of cars, not miles per gallon. H0: am and vs are independent.

tab <- table(mtcars$am, mtcars$vs)
chisq.test(tab)
## 
##  Pearson's Chi-squared test with Yates' continuity correction
## 
## data:  tab
## X-squared = 0.34754, df = 1, p-value = 0.5555

The p-value is about 0.56. These counts are not evidence against independence of am and vs. A large p-value is part of an honest report. It is not a failed analysis.

Example 2. Species and sex are both categories. Drop penguins with sex missing, then count the combinations. H0: species and sex are independent.

peng_sex <- penguins |>
  filter(!is.na(sex))

chisq.test(table(peng_sex$species, peng_sex$sex))
## 
##  Pearson's Chi-squared test
## 
## data:  table(peng_sex$species, peng_sex$sex)
## X-squared = 0.048607, df = 2, p-value = 0.976

Chi-square test (Organic Chemistry Tutor) is a worked table of counts in this same form.

Whether an extra predictor helps

Use anova() on two nested lm() fits when the smaller model is a special case of the larger one. H0: the extra terms are zero. The call is anova(small, big). aov() is the fit for group means. anova() is the comparison of two models. The names are easy to swap, and they are not the same function. A single coefficient inside summary(lm()) is its own test. That row asks whether that coefficient is zero, holding the other predictors fixed. Note 11.1 reads that output, including curves and predictors whose units are far apart.

Example 1. Two nested models for mpg. The second adds horsepower to a model that already has weight. H0: once wt is in the model, hp does not improve the fit.

m1 <- lm(mpg ~ wt, data = mtcars)
m2 <- lm(mpg ~ wt + hp, data = mtcars)
cmp <- anova(m1, m2)
cmp
## Analysis of Variance Table
## 
## Model 1: mpg ~ wt
## Model 2: mpg ~ wt + hp
##   Res.Df    RSS Df Sum of Sq      F   Pr(>F)   
## 1     30 278.32                                
## 2     29 195.05  1    83.274 12.381 0.001451 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Read the p-value as evidence against that H0, next to the change in residual sum of squares.

Example 2. Two nested models for bill length. The second adds body mass to a model that already has flipper length. Keep only birds measured on all three variables, so both fits use the same rows. H0: once flipper length is in the model, body mass does not improve the fit.

peng_m <- penguins |>
  filter(
    !is.na(bill_length_mm),
    !is.na(flipper_length_mm),
    !is.na(body_mass_g)
  )

b1 <- lm(bill_length_mm ~ flipper_length_mm, data = peng_m)
b2 <- lm(bill_length_mm ~ flipper_length_mm + body_mass_g, data = peng_m)
anova(b1, b2)
## Analysis of Variance Table
## 
## Model 1: bill_length_mm ~ flipper_length_mm
## Model 2: bill_length_mm ~ flipper_length_mm + body_mass_g
##   Res.Df    RSS Df Sum of Sq      F Pr(>F)
## 1    340 5787.8                           
## 2    339 5764.6  1    23.179 1.3631 0.2438

3. The menu on one page

The hypothesis is about The data look like The call H0 in words
one group versus a known number (one-sample t-test) one numeric column, σ unknown t.test(x, mu = 1.5) the mean equals 1.5
one group versus a known number, and σ is known (z-test) one numeric column and a known population sd (mean(x) - mu) / (sigma / sqrt(n)), then pnorm() the mean equals that number
two unrelated groups (independent t-test) a number and a two-level group t.test(y ~ group) the two means are equal
the same units twice (paired t-test) two numeric columns, paired by row t.test(before, after, paired = TRUE) the mean change is 0
three or more group means a number and a factor with 3+ levels aov(y ~ group) then summary() all the means are equal
two numeric variables moving together two numeric columns cor.test(x, y) the correlation is 0
one or two proportions counts of successes and sample sizes prop.test() the proportion equals the guess, or the two proportions are equal
two categorical variables a table of counts chisq.test(table) the two factors are independent
whether an extra predictor helps two nested lm() fits anova(small, big) the extra terms are zero

4. The p-value, the estimate, and the interval

State H0 in words before you look at the number.

For the penguin pair: mean bill length is the same for Adelie and Gentoo. For mtcars: mean mpg is the same for the two transmission codes.

The p-value is the chance of a result at least this far from H0, in a world where H0 is true. A small p-value means the data would be surprising if H0 were true, so the data are evidence against H0. A p-value of 0.001 on the miles-per-gallon test means: if the two transmission groups really had the same mean, a gap this large would be rare.

Read it next to the other two numbers, not alone.

  • The estimate is the size. In the mpg test it is the two group means, about 17 and about 24. That gap is the finding.
  • The confidence interval is the range of gaps that remain compatible with the data. The mpg interval for the difference runs from about −11 to about −3. The whole interval sits away from zero, which matches a small p-value. An interval that covers zero matches a large p-value.
  • The p-value is the surprise under H0. It is not the probability that H0 is true, and it is not the size of the gap. A huge sample can make a tiny, unimportant gap produce a tiny p-value. A small sample can miss a real gap and leave a large p-value. A large p-value is a weak case against H0. It does not prove that H0 is true.

0.05 is a common reporting cutoff. It is not a property of the data. Report the p-value, the estimates, and the interval, then write the sentence. Do not replace that sentence with “significant” or “not significant.”

The test has to be the one you chose in section 2. Trying several tests and keeping the smallest p-value makes that p-value mean something else.


5. Practice

  1. Write H0 in words, then a boxplot and a two-sample t.test(). Use mpg ~ factor(am) in mtcars, or Adelie vs Gentoo bill length in penguins (filter, then droplevels()). Save the object. In one sentence, give the two means, the direction of the gap, and the p-value as evidence against H0.
  2. aov() of a numeric variable by a factor with three or more levels (bill_length_mm ~ species, or mpg ~ factor(cyl), or Sepal.Length ~ Species). Save the fit. State H0 in words. A small p-value says the means are not all equal. Name the further comparison you would still need in order to say which group differs from which.
  3. cor.test() for wt and mpg in mtcars. State H0. Put the correlation estimate next to the p-value in one sentence.