Statistical tests

Day 3 - Introduction to Data Analysis with R

Selina Baldauf

Freie Universität Berlin - Theoretical Ecology

October 17, 2026

General approach

Tests to compare two groups

t-test

  • Compares the means of two groups
  • Suitable for roughly normal data, or for larger samples
  • 2 versions: Student’s (equal variance) and Welch’s t-test
    • Welch’s t-test is a good default

Wilcoxon rank-sum test

  • Compares ranks: does one group tend to have larger values?
  • Useful for ordinal data, skewed small samples, or outliers

The data: iris

Question: Does the sepal width differ between I. versicolor and I. virginica?

Reproduce the data
flowers <- as_tibble(iris) |>
  filter(Species %in% c("versicolor", "virginica")) |>
  select(sepal_width = Sepal.Width, species = Species) |>
  droplevels()
flowers
#> # A tibble: 100 × 2
#>    sepal_width species   
#>          <dbl> <fct>     
#>  1         3.2 versicolor
#>  2         3.2 versicolor
#>  3         3.1 versicolor
#>  4         2.3 versicolor
#>  5         2.8 versicolor
#>  6         2.8 versicolor
#>  7         3.3 versicolor
#>  8         2.4 versicolor
#>  9         2.9 versicolor
#> 10         2.7 versicolor
#> # ℹ 90 more rows

Image from medium.com

Sepal width (in cm) of 50 flowers from each of two iris species

First look at the data

flowers |>
  summarize(
    n = n(),
    mean = mean(sepal_width),
    sd = sd(sepal_width),
    .by = species
  )
#> # A tibble: 2 × 4
#>   species        n  mean    sd
#>   <fct>      <int> <dbl> <dbl>
#> 1 versicolor    50  2.77 0.314
#> 2 virginica     50  2.97 0.322
Code for the boxplot
ggplot(flowers, aes(x = species, y = sepal_width)) +
  geom_boxplot() +
  geom_point(
    position = position_jitter(width = 0.08, height = 0, seed = 123),
    alpha = 0.6
  ) +
  labs(x = "Species", y = "Sepal width (cm)")

Prepare the group vectors

Most test functions take the values of each group as a vector

versicolor <- filter(flowers, species == "versicolor")$sepal_width
virginica <- filter(flowers, species == "virginica")$sepal_width


versicolor
#>  [1] 3.2 3.2 3.1 2.3 2.8 2.8 3.3 2.4 2.9 2.7 2.0 3.0 2.2 2.9 2.9 3.1 3.0 2.7 2.2
#> [20] 2.5 3.2 2.8 2.5 2.8 2.9 3.0 2.8 3.0 2.9 2.6 2.4 2.4 2.7 2.7 3.0 3.4 3.1 2.3
#> [39] 3.0 2.5 2.6 3.0 2.6 2.3 2.7 3.0 2.9 2.9 2.5 2.8

Shapiro-Wilk test for normality

\(H_0\): The data come from a normal distribution

shapiro.test(versicolor)
#> 
#>  Shapiro-Wilk normality test
#> 
#> data:  versicolor
#> W = 0.97413, p-value = 0.338
shapiro.test(virginica)
#> 
#>  Shapiro-Wilk normality test
#> 
#> data:  virginica
#> W = 0.96739, p-value = 0.1809
  • A large p-value: no evidence against normality, can not reject \(H_0\)
  • With large samples, very small deviations can give small p-values
  • Always look at the data as well

Normality with QQ-plots

Points should roughly follow the line. Look at the tails and at unusual observations.

ggpubr::ggqqplot(versicolor)

ggpubr::ggqqplot(virginica)

Both species: no clear deviation from normality

What does non-normal data look like?

Compare two means: Welch’s t-test

\(H_0\): The means of the two groups do not differ

t.test(versicolor, virginica)
#> 
#>  Welch Two Sample t-test
#> 
#> data:  versicolor and virginica
#> t = -3.2058, df = 97.927, p-value = 0.001819
#> alternative hypothesis: true difference in means is not equal to 0
#> 95 percent confidence interval:
#>  -0.33028364 -0.07771636
#> sample estimates:
#> mean of x mean of y 
#>     2.770     2.974
  • t: test statistic (t = 0 if the means are equal)
  • p-value: How likely is a difference at least this large if the means were equal?
  • Reject \(H_0\)

Mean sepal width was 0.20 cm smaller in I. versicolor than in I. virginica (Welch’s t-test, \(t_{97.9}\) = -3.21, p = 0.002).

Wilcoxon rank-sum test

\(H_0\): Neither group tends to have larger values than the other

  • All values are ranked from smallest to largest
  • The test compares the ranks of the two groups
  • Demonstration only: the iris data don’t need a rank-based test, t-test was fine here
wilcox.test(versicolor, virginica)
#> 
#>  Wilcoxon rank sum test with continuity correction
#> 
#> data:  versicolor and virginica
#> W = 841, p-value = 0.004572
#> alternative hypothesis: true location shift is not equal to 0

Sepal width tended to be smaller in I. versicolor than in I. virginica (Wilcoxon rank-sum test, W = 841, p = 0.005).

Paired observations

Examples of paired observations:

  • Blood pressure of patients before and after medication
  • Difference in sleep quality of people as children and adults
  • Biodiversity in rivers before and after a power plant …

In sleep, the same 10 people received two drugs (extra: extra sleep in hours)

Reproduce the data
sleep_paired <- sleep |>
  pivot_wider(
    names_from = group,
    names_prefix = "drug_",
    values_from = extra
  )
sleep_paired
#> # A tibble: 10 × 3
#>    ID    drug_1 drug_2
#>    <fct>  <dbl>  <dbl>
#>  1 1        0.7    1.9
#>  2 2       -1.6    0.8
#>  3 3       -0.2    1.1
#>  4 4       -1.2    0.1
#>  5 5       -0.1   -0.1
#>  6 6        3.4    4.4
#>  7 7        3.7    5.5
#>  8 8        0.8    1.6
#>  9 9        0      4.6
#> 10 10       2      3.4

Paired observations

t.test(
  sleep_paired$drug_1,
  sleep_paired$drug_2,
  paired = TRUE
)
#> 
#>  Paired t-test
#> 
#> data:  sleep_paired$drug_1 and sleep_paired$drug_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

Also: wilcox.test(..., paired = TRUE)

People slept 1.58 h longer with drug 2 than with drug 1 (paired t-test, \(t_9\) = -4.06, p = 0.003).

Visualizing test results

Boxplot to show differences

ggplot(
  flowers,
  aes(x = species, y = sepal_width)
) +
  geom_boxplot()

Add a test with geom_signif()

The ggsignif package adds significance levels to a ggplot

# install.packages("ggsignif")
library(ggsignif)

ggplot(
  flowers,
  aes(x = species, y = sepal_width)
) +
  geom_boxplot() +
  geom_signif(
    comparisons = list(
      c("versicolor", "virginica")
    ),
    test = "t.test",
    map_signif_level = TRUE
  )

  • test = "t.test": Welch’s t-test (the default is a Wilcoxon test)
  • map_signif_level = TRUE: stars, FALSE: p-value

Plot means with stat_summary()

ggplot(
  flowers,
  aes(x = species, y = sepal_width)
) +
  stat_summary()

  • By default, stat_summary() shows the mean ± standard error (SE)

Style means and error bars

ggplot(
  flowers,
  aes(x = species, y = sepal_width)
) +
  stat_summary(
    fun.data = mean_se,
    geom = "errorbar",
    width = 0.15
  ) +
  stat_summary(
    fun = mean,
    geom = "point",
    color = "#28a87d",
    size = 4
  )

  • fun.data for error bars, fun for points

Barplots with error bars

ggplot(
  flowers,
  aes(x = species, y = sepal_width)
) +
  stat_summary(
    fun.data = mean_se,
    geom = "errorbar",
    width = 0.15
  ) +
  stat_summary(
    fun = mean,
    geom = "bar",
    fill = "#28a87d",
    width = 0.65
  )

Add the test to the barplot

ggplot(
  flowers,
  aes(x = species, y = sepal_width)
) +
  stat_summary(
    fun.data = mean_se,
    geom = "errorbar",
    width = 0.15
  ) +
  stat_summary(
    fun = mean,
    geom = "bar",
    fill = "#28a87d",
    width = 0.65
  ) +
  geom_signif(
    comparisons = list(
      c("versicolor", "virginica")
    ),
    test = "t.test",
    map_signif_level = TRUE
  )

Comparing three groups

Actually, there were three species

Question: Does the sepal width differ between the three iris species?

Reproduce the data
flowers_all <- as_tibble(iris) |>
  select(sepal_width = Sepal.Width, species = Species)
flowers_all |>
  summarize(
    n = n(),
    mean = mean(sepal_width),
    .by = species
  )
#> # A tibble: 3 × 3
#>   species        n  mean
#>   <fct>      <int> <dbl>
#> 1 setosa        50  3.43
#> 2 versicolor    50  2.77
#> 3 virginica     50  2.97

Could we just run 3 separate t-tests?

Two kinds of errors

Every test decision can be wrong in two ways:

\(H_0\) is true (no difference) \(H_0\) is false (real difference)
Reject \(H_0\) Type I error: false positive (probability α) Correct
Do not reject \(H_0\) Correct Type II error: false negative
  • With α = 0.05, we accept a 5% risk of a false positive
  • Multiple testing increases the risk of a type I error

Error-inflation with multiple testing

  • For one test: Chance of false positive is 5% (at α = 0.05)
  • This error potential increases with multiple tests:

\[P(\text{at least one false positive}) = 1 - (1 - \alpha)^k\]

with \(k\) = number of tests

Number of tests Chance of at least one false positive
1 5%
3 14.3%
10 40.1%

Solution: p-value correction for multiple testing

Pairwise comparisons in R

pairwise.t.test(
  flowers_all$sepal_width,
  flowers_all$species,
  pool.sd = FALSE
)
#> 
#>  Pairwise comparisons using t tests with non-pooled SD 
#> 
#> data:  flowers_all$sepal_width and flowers_all$species 
#> 
#>            setosa  versicolor
#> versicolor 7.5e-15 -         
#> virginica  9.1e-09 0.0018    
#> 
#> P value adjustment method: holm
  • pool.sd = FALSE: Welch’s t-test for each pair (the default uses one shared SD across all groups)
  • The p-values are already adjusted (Holm method is the default)
  • Rank-based alternative: pairwise.wilcox.test()

Add the adjusted p-values to a plot

geom_signif can’t run pairwise tests, so we need to add p-values manually.

ggplot(
  flowers_all,
  aes(x = species, y = sepal_width)
) +
  geom_boxplot() +
  geom_signif(
    comparisons = list(
      c("setosa", "versicolor"),
      c("setosa", "virginica"),
      c("versicolor", "virginica")
    ),
    annotations = c(
      "p = 7.5e-15",
      "p = 9.1e-09",
      "p = 0.0018"
    ),
    step_increase = 0.1,
    tip_length = 0.02
  )

  • annotations: show our adjusted p-values (no new tests)
  • step_increase: stack the brackets

Extract the p-values automatically

Typing p-values by hand is error-prone. Extract them with p["row", "column"]:

pairwise_results <- pairwise.t.test(
  flowers_all$sepal_width,
  flowers_all$species,
  pool.sd = FALSE
)
p <- pairwise_results$p.value

comparisons <- list(
  c("setosa", "versicolor"),
  c("setosa", "virginica"),
  c("versicolor", "virginica")
)
adjusted_p <- c(
  p["versicolor", "setosa"],
  p["virginica", "setosa"],
  p["virginica", "versicolor"]
)
p_labels <- paste(
  "p =",
  format.pval(adjusted_p, digits = 2)
)
ggplot(
  flowers_all,
  aes(x = species, y = sepal_width)
) +
  geom_boxplot() +
  geom_signif(
    comparisons = comparisons,
    annotations = p_labels,
    step_increase = 0.1,
    tip_length = 0.02
  )

Add the test results to the barplot

ggplot(
  flowers_all,
  aes(x = species, y = sepal_width)
) +
  stat_summary(
    fun.data = mean_se,
    geom = "errorbar",
    width = 0.15
  ) +
  stat_summary(
    fun = mean,
    geom = "bar",
    fill = "#28a87d",
    width = 0.65
  ) +
  geom_signif(
    comparisons = comparisons,
    annotations = p_labels,
    step_increase = 0.1,
    tip_length = 0.02
  )

Now you

Task (45 min)

Statistical tests with penguins

Find the task description here