Analysis of Variance (ANOVA)

F-Distribution • One-Way ANOVA • Multiple Comparisons • Kruskal–Wallis

Semester Finale!

This is our last chapter. We are now upgrading from comparing two means (T-Tests) to comparing multiple means simultaneously using ANOVA.

Today we build the full ANOVA toolkit: understand the F-distribution, run a one-way ANOVA from sums of squares, report the ANOVA table, interpret decisions, and follow up with Tukey or the nonparametric Kruskal–Wallis test.

The Coffee Experiment

Light
Roast
Medium
Roast
Dark
Roast

Scenario: We ask 30 people to rate coffee acidity (0–100).
10 people drink Light, 10 Medium, 10 Dark.

The Question

We calculate the average scores:

  • Light: 78
  • Medium: 82
  • Dark: 75

“Are these taste differences statistically significant, or could they have happened by random chance?”

Why not just compare pairs?

Why can't we just run t‑tests for Light vs Medium, Medium vs Dark, etc.?

The Problem: Exploding Error Rates

Every time you run a test, you risk a Type I Error (false alarm) of 5%.

$$P(\text{No Error in 1 Test}) = 0.95$$ $$P(\text{No Error in 3 Tests}) = 0.95 \times 0.95 \times 0.95 \approx 0.86$$

Error risk jumps from 5% to ~14%!

Solution: ANOVA tests all groups simultaneously with a single error rate.

How ANOVA Works: Signal vs. Noise

Variation 1: “Between” Groups

How different are the group averages from each other?

Signal: group means are sending different messages.

Large between-group variation means the group centers are separated enough to notice.

Variation 2: “Within” Groups

How spread out is the data inside each specific group?

Noise: individual scores vary even inside the same group.

Large within-group variation makes true group differences harder to hear.

$$ F = \frac{\text{Variance Between Groups (Signal)}}{\text{Variance Within Groups (Noise)}} $$

Active Checkpoint: Listen for the Ratio

Think-Pair-Share

If the within-group spread suddenly doubled but the group means stayed in the same places, what would happen to \(F\)?

Be ready to explain it using the words signal, noise, numerator, and denominator.

The Math The Code

Translating the statistical model into R syntax using aov().

Mathematical Model

$$y = \mu + \tau + \epsilon$$
  • \(y\): The Response (Taste Score)
  • \(\tau\): The Factor (Roast Type)
  • \(\epsilon\): The Error

R Implementation

# Syntax: aov(Response ~ Factor)

model <- aov(Score ~ Roast, data = coffee_data)

# View Results
summary(model)
  • The ~ symbol (tilde) represents the equals sign in the formula.
  • “Score is explained by Roast.”
Note: We strictly use aov() for standard ANOVA to mirror the linear model structure.

Part 1: The F-Distribution & Visualizing F-Curves

Basic Properties of F-Curves

  • Total area under curve = 1.
  • Starts at 0, extends right (no negatives).
  • Right-skewed. Shape depends on \(df_1\) and \(df_2\).

Simulated F-Curve Shape

Adjust Degrees of Freedom:

2
10

Observation:
Notice how the peak shifts and the tail thickness changes. As \(df\) increases, the curve becomes less skewed and more symmetric (approaching Normal).

Quick R Commands for the F-Distribution

When you know \(df_1\), \(df_2\), and \(F_0\)

  • Critical values come from the right tail.
  • P-values for ANOVA are also right-tail areas.
  • In R, \(df_1\) is the numerator df and \(df_2\) is the denominator df.
# Critical value for alpha = 0.05
qf(p = 0.95, df1 = 2, df2 = 6)

# P-value from an observed F-statistic
1 - pf(1.69, df1 = 2, df2 = 6)

# Draw an F-curve
curve(df(x, df1 = 2, df2 = 6), from = 0, to = 6)
abline(v = qf(0.95, 2, 6), col = "red", lty = 2)
Memory hook: ANOVA asks whether \(F_0\) is unusually large, so we look to the right.

Part 2: One-Way ANOVA — Setup & Definitions

Assumptions

  • Simple random samples from each population.
  • Independent samples across populations.
  • Normal populations within each group.
  • Equal standard deviations across groups.

Mean Squares

Treatment Mean Square (Signal): \(\mathrm{MSTR} = \frac{\mathrm{SSTR}}{k-1}\)

Error Mean Square (Noise): \(\mathrm{MSE} = \frac{\mathrm{SSE}}{n-k}\)


F-Statistic: \( \displaystyle F = \frac{\mathrm{MSTR}}{\mathrm{MSE}} \)

Take samples from \(k\) populations, compute group means, and compare their variation to the variation within groups.

Active Checkpoint: Predict the Direction

Quick Vote

Suppose two classes have very different average exam scores, but each class also has huge student-to-student variability. Should the \(F\)-statistic necessarily be large?

Answer in one sentence: what has to be true about \(\mathrm{MSTR}\) compared with \(\mathrm{MSE}\)?

Visualizing "Between" vs "Within"

If Between variation is large compared to Within variation, the groups are likely different (Large F).

F-Stat estimate: Low

The ANOVA Identity & Sums of Squares

\( \displaystyle \mathrm{SST} = \mathrm{SSTR} + \mathrm{SSE} \)

Total SS (SST)

Defining: \( \sum (x_i - \bar{x})^2 \)
Computing: \( \sum x_i^2 - \dfrac{(\sum x_i)^2}{n} \)

Treatment SS (SSTR)

Defining: \( \sum n_j(\bar{x}_j - \bar{x})^2 \)
Computing: \( \sum \dfrac{T_j^2}{n_j} - \dfrac{(\sum x_i)^2}{n} \)

Error SS (SSE)

Defining: \( \sum (n_j - 1)s_j^2 \)     Computing: \( \mathrm{SST} - \mathrm{SSTR} \)

Notation: \(n\) total observations, \( \bar{x} \) grand mean, \( n_j \) group sizes, \( \bar{x}_j \) group means, \( s_j^2 \) group variances, \( T_j \) group totals.

Active Checkpoint: Sort the Ingredients

Partner Check

Place each quantity into the ANOVA table before seeing the table: \(\mathrm{SSTR}\), \(\mathrm{SSE}\), \(k-1\), \(n-k\), \(\mathrm{MSTR}\), \(\mathrm{MSE}\).

Which row measures signal? Which row measures noise?

One-Way ANOVA Table Structure & Pitfall

Source df SS (Sum of Squares) MS (Mean Square) F-statistic
Treatment \(k-1\) \(\mathrm{SSTR}\) \(\mathrm{MSTR}=\mathrm{SSTR}/(k-1)\) \(F=\mathrm{MSTR}/\mathrm{MSE}\)
Error \(n-k\) \(\mathrm{SSE}\) \(\mathrm{MSE}=\mathrm{SSE}/(n-k)\)
Total \(n-1\) \(\mathrm{SST}\)
Pitfall: Mixing up the df's!
Numerator df \(df_1 = k-1\) (Treatment row) and Denominator df \(df_2 = n-k\) (Error row). \(F_{(2,12)}\) and \(F_{(12,2)}\) are completely different curves!

Hypothesis Test Procedure

  1. State Hypotheses: \(H_0:\mu_1=\mu_2=\cdots=\mu_k\); \(H_a:\) not all means equal.
  2. Choose \(\alpha\) (significance level).
  3. Compute \(F_0=\mathrm{MSTR}/\mathrm{MSE}\) using the ANOVA table.
  4. Decision — Critical Value: Reject \(H_0\) if \(F_0 > F_\alpha\) with df \((k-1,\,n-k)\).
  5. Decision — P-Value: Reject \(H_0\) if \(P \le \alpha\).
  6. Interpret: Explain the result in context.

Full Walkthrough: AI Coding Benchmarks

Scenario: The AI Coding Showdown

As Artificial Intelligence continues to evolve rapidly, major tech companies are fiercely competing for developer adoption. A leading tech publication wants to determine if there is a statistically significant difference in the coding capabilities of three flagship models: Claude 3.5, ChatGPT-4o, and Gemini 1.5.

They subjected each model to a rigorous battery of 8 complex algorithmic challenges. The output was evaluated by senior engineers on a scale of 0 to 100 based on efficiency, accuracy, and code readability. Is one model truly superior, or are the observed differences merely random statistical noise? Let's use ANOVA to find out!


Step 1: The Data & Hypotheses

Claude 3.5

92, 94, 91, 95, 93, 93, 94, 92

Mean \(\bar{x}_1 = 93\)

ChatGPT-4o

88, 90, 87, 89, 91, 89, 88, 90

Mean \(\bar{x}_2 = 89\)

Gemini 1.5

85, 87, 86, 88, 84, 86, 85, 87

Mean \(\bar{x}_3 = 86\)

Grand Mean \(\bar{\bar{x}} = \frac{93+89+86}{3} = 89.33\)

Hypotheses: \(H_0: \mu_{C} = \mu_{Chat} = \mu_{G}\) vs. \(H_a:\) At least one differs.


Step 2: Partitioning the Variance (Flowchart)

Total Variation (SST)
Between Models (SSTR)
The Signal
Within Models (SSE)
The Noise

Step 3a: Within-Group Variation (SSE)

How much does each score deviate from its own model's mean?

Model (\(\bar{x}_i\)) Raw Scores (\(x\)) Deviations \((x - \bar{x}_i)\) Squared \((x - \bar{x}_i)^2\) Sum
Claude (93)92, 94, 91, 95, 93, 93, 94, 92-1, 1, -2, 2, 0, 0, 1, -11, 1, 4, 4, 0, 0, 1, 112
ChatGPT (89)88, 90, 87, 89, 91, 89, 88, 90-1, 1, -2, 0, 2, 0, -1, 11, 1, 4, 0, 4, 0, 1, 112
Gemini (86)85, 87, 86, 88, 84, 86, 85, 87-1, 1, 0, 2, -2, 0, -1, 11, 1, 0, 4, 4, 0, 1, 112
Total Error Sum of Squares (SSE): 36

Step 3b: Between-Group Variation (SSTR)

How much does each model's mean deviate from the Grand Mean (\(\bar{\bar{x}} = 89.33\))?

Model \(n\) Model Mean (\(\bar{x}_i\)) Deviation \((\bar{x}_i - \bar{\bar{x}})\) Squared \((\bar{x}_i - \bar{\bar{x}})^2\) Weighted \(n(\bar{x}_i - \bar{\bar{x}})^2\)
Claude8933.66713.444107.55
ChatGPT889-0.3330.1110.89
Gemini886-3.33311.11188.89
Total Treatment Sum of Squares (SSTR): 197.33

Step 4: The ANOVA Table

SourcedfSSMSF
Treatment (Between)\(k-1 = 3-1 = 2\)\(197.33\)\(\frac{197.33}{2} = 98.67\)\(\frac{98.67}{1.71} = 57.56\)
Error (Within)\(n-k = 24-3 = 21\)\(36.00\)\(\frac{36}{21} = 1.71\)
Total\(n-1 = 23\)\(233.33\)

Step 5: Decision

Our F-Statistic is 57.56.
Looking at the F-distribution for \(df=(2, 21)\) with \(\alpha=0.05\), the critical value is \(F_{crit} = 3.47\).

Conclusion: Since \(57.56 > 3.47\), we Reject \(H_0\). There is overwhelming evidence that the true mean coding benchmark scores of Claude 3.5, ChatGPT-4o, and Gemini 1.5 are not all equal!

Example: Teaching Methods in R

Scenario

Compare exam scores across three study designs: Traditional, Online, and Peer-to-Peer.

  • Traditional: 75, 82, 68
  • Online: 90, 78, 85
  • Peer-to-Peer: 88, 92, 80

Hypotheses: \(H_0:\mu_1=\mu_2=\mu_3\); \(H_a:\) at least one mean differs.

x1 <- c(75, 82, 68)
x2 <- c(90, 78, 85)
x3 <- c(88, 92, 80)

Score <- c(x1, x2, x3)
Method <- factor(rep(c("Traditional", "Online", "Peer"), each = 3))
scores_data <- data.frame(Score, Method)

model <- aov(Score ~ Method, data = scores_data)
summary(model)

boxplot(Score ~ Method, data = scores_data)

After the Test: How Large is the Effect?

\(\displaystyle \eta^2 = \frac{SS_{\text{between}}}{SS_{\text{total}}} = \frac{\mathrm{SSTR}}{\mathrm{SST}}\)

Interpretation

\(\eta^2\) is the proportion of total variation explained by the group factor. A small p-value says an effect is statistically detectable; \(\eta^2\) says how much variation the factor accounts for.

model_stats <- summary(model)
eta_squared <- model_stats[[1]]["Method", "Sum Sq"] /
               sum(model_stats[[1]][, "Sum Sq"])

eta_squared

Multiple Comparisons — Tukey Method

Purpose: After ANOVA shows not all means are equal, determine which pairs differ.

Procedure

  • Choose family confidence level \(1-\alpha\).
  • Find \(q_\alpha\) for the q-curve with \(k\) groups and \(\nu=n-k\) df.
  • Compute CIs for all pairs \(i
\( (\bar{x}_i-\bar{x}_j) \pm \dfrac{q_\alpha}{\sqrt{2}}\; s \sqrt{\dfrac{1}{n_i}+\dfrac{1}{n_j}} \),   where \( s=\sqrt{\mathrm{MSE}} \).

Decision & Summary

  • Declare means different if the CI for \(\mu_i-\mu_j\) excludes 0.
  • Rank sample means and underline groups that are not declared different.

Active Checkpoint: What Did ANOVA Actually Tell Us?

One-Minute Write

If ANOVA rejects \(H_0\), can we immediately say that every pair of group means is different?

Write the correct conclusion in context, then name the follow-up tool we use to compare pairs.

The Kruskal–Wallis Test

Overview

A nonparametric alternative to one-way ANOVA when normality is doubtful but group shapes are similar.

Distribution of \(K\)

If the \(k\) distributions have the same shape and \(H_0\) (equal means) is true, then \(K\) is approximately \( \chi^2 \) with df \(k-1\).

Test Procedure

  1. Assumptions: SRS, independence, same-shape populations, all group sizes \(\ge 5\).
  2. Hypotheses: \(H_0:\mu_1=\cdots=\mu_k\); \(H_a:\) not all means equal.
  3. Choose \(\alpha\).
  4. Compute statistic: rank all data, then \( \displaystyle K = \frac{12}{n(n+1)} \sum_{j=1}^{k} \frac{R_j^2}{n_j} - 3(n+1) \), where \(R_j\) is the rank sum in group \(j\).
  5. Decision: Critical value: reject if \(K_0 > \chi^2_\alpha\) with df \(k-1\). P-value: reject if \(P \le \alpha\).
Which to use? If reasonably normal & equal variances ⇒ use One-Way ANOVA. If not normal (but same shape) ⇒ use Kruskal–Wallis.

Choosing the Right Group Comparison

Use One-Way ANOVA when...

  • Groups are independent.
  • The response is roughly normal within groups.
  • Group variances are reasonably similar.

Consider alternatives when...

  • Variances are very unequal: Welch's ANOVA.
  • Small samples are strongly non-normal: Kruskal-Wallis.
  • Data are paired or repeated: not one-way ANOVA.
Design first: the correct method depends on how the data were collected, not just how the numbers look.

Example: Kruskal-Wallis in R

Scenario

Recovery times are skewed, so we compare three treatment groups using ranks instead of raw means.

  • Treatment A: 5, 7, 6, 8, 4
  • Treatment B: 12, 9, 11, 8, 10
  • Treatment C: 6, 8, 7, 9, 5
treat_A <- c(5, 7, 6, 8, 4)
treat_B <- c(12, 9, 11, 8, 10)
treat_C <- c(6, 8, 7, 9, 5)

recovery <- c(treat_A, treat_B, treat_C)
groups <- factor(rep(c("A", "B", "C"), each = 5))

kruskal.test(recovery ~ groups)
boxplot(recovery ~ groups)

Worked Example (Step-by-Step)

Scenario

Three groups (A, B, C) each with n=5 observations. Reported summaries are:
Group A: \(\bar x_1=10\), \(s_1=1.2\)  |   Group B: \(\bar x_2=13\), \(s_2=1.2\)  |   Group C: \(\bar x_3=12\), \(s_3=1.2\).

Goal

Test \(H_0:\mu_1=\mu_2=\mu_3\) at \(\alpha=0.05\) using one-way ANOVA (from summary stats).

Step 1: Totals and Grand Mean

\( N = 5+5+5 = 15,\quad k=3,\quad \bar x_G = \dfrac{5(10)+5(13)+5(12)}{15} = \dfrac{175}{15} = \dfrac{35}{3} \approx 11.6667. \)

Step 2: Sums of Squares

Treatment (SSTR)
\( \displaystyle \mathrm{SSTR} = \sum n_j(\bar x_j-\bar x_G)^2 = 5\!\left(\!10-\tfrac{35}{3}\!\right)^{\!2} + 5\!\left(\!13-\tfrac{35}{3}\!\right)^{\!2} + 5\!\left(\!12-\tfrac{35}{3}\!\right)^{\!2} = \frac{70}{3} \approx 23.3333. \)
Error (SSE)
\( \displaystyle \mathrm{SSE} = \sum (n_j-1)s_j^2 = 3\times 4 \times (1.2)^2 = 12 \times 1.44 = 17.28. \)

Step 3: Degrees of Freedom & Mean Squares

\( \displaystyle df_1 = k-1 = 2,\quad df_2 = N-k = 12. \)
\( \displaystyle \mathrm{MSTR} = \frac{\mathrm{SSTR}}{df_1} = \frac{70/3}{2} = \frac{35}{3} \approx 11.6667, \quad \mathrm{MSE} = \frac{\mathrm{SSE}}{df_2} = \frac{17.28}{12} = 1.44. \)

Step 4: Test Statistic and Decision

\( \displaystyle F_0 = \frac{\mathrm{MSTR}}{\mathrm{MSE}} = \frac{11.6667}{1.44} \approx 8.10. \)
Critical value \( F_{0.05;(2,12)} \approx 3.89 \Rightarrow \) since \( 8.10 > 3.89 \), Reject \(H_0\).
There is strong evidence that at least one population mean differs. (P-value \( < 0.01 \).)

R: Math-Only One-Way ANOVA (from Summaries)

No aov(), no external libraries. Enter group sizes, means, and sds; the code mirrors the hand-calculation steps.

# ---- One-way ANOVA from summary statistics (no aov, no libraries) ----
# Inputs: group sizes n_j, sample means xbar_j, sample sds s_j
n    <- c(5, 5, 5)
xbar <- c(10, 13, 12)
s    <- c(1.2, 1.2, 1.2)
alpha <- 0.05

# 1) Totals and grand mean
N  <- sum(n)
k  <- length(n)
xG <- sum(n * xbar) / N

# 2) Sums of squares (defining formulas)
SSTR <- sum( n * (xbar - xG)^2 )
SSE  <- sum( (n - 1) * (s^2) )
SST  <- SSTR + SSE  # identity check

# 3) Degrees of freedom
df1 <- k - 1         # treatment
df2 <- N - k         # error

# 4) Mean squares
MSTR <- SSTR / df1
MSE  <- SSE  / df2

# 5) F statistic, p-value, and critical value
F0    <- MSTR / MSE
pval  <- 1 - pf(F0, df1, df2)   # upper-tail area
Fcrit <- qf(1 - alpha, df1, df2)

# 6) Optional effect size (eta-squared)
eta2 <- SSTR / SST

# 7) Report the usual values
N; k; xG
SSTR; SSE; SST
df1; df2; MSTR; MSE
F0; pval; Fcrit
eta2
Tip: Replace n, xbar, and s with your own summary statistics to mirror the same hand-steps used in class.

R: Math-Only One-Way ANOVA (from Raw Data)

No aov(), no external libraries. Put each group’s numeric vector into the list. Add/remove items to change the number of groups (works for 2+ groups).

# ---- One-way ANOVA from raw data (math-only, no aov, no libraries) ----
# Put each group's numeric vector in the list below. Add/remove items = change number of groups.
groups <- list(
  A = c(10,  9, 11, 10, 10),
  B = c(13, 14, 12, 13, 13),
  C = c(12, 12, 12, 11, 13),
  D = c( 9, 10,  8, 10,  9)
)

alpha <- 0.05

# 1) Create summary stats for each group (n_j, xbar_j, s_j)
n    <- sapply(groups, length)
xbar <- sapply(groups, mean)
s    <- sapply(groups, sd)               # sample sd (denominator n-1)

# 2) Totals and grand mean
N  <- sum(n)
k  <- length(n)
xG <- sum(n * xbar) / N

# 3) Sums of squares (defining formulas)
SSTR <- sum( n * (xbar - xG)^2 )
SSE  <- sum( (n - 1) * (s^2) )
SST  <- SSTR + SSE

# 4) Degrees of freedom
df1 <- k - 1
df2 <- N - k

# 5) Mean squares
MSTR <- SSTR / df1
MSE  <- SSE  / df2

# 6) F-statistic, p-value, critical value
F0    <- MSTR / MSE
pval  <- 1 - pf(F0, df1, df2)
Fcrit <- qf(1 - alpha, df1, df2)

# 7) Optional effect size
eta2  <- SSTR / SST

# 8) Values to read off
N; k; xbar; s; xG
SSTR; SSE; SST
df1; df2; MSTR; MSE
F0; pval; Fcrit; eta2
Tip: Rename keys (A, B, C, D) or add/remove items in groups. The code automatically adapts the number of groups and mirrors the hand-calculation workflow.