# ============================================
# ANOVA and Post-hoc Analysis: GDP per Capita by Continent
# Using the Gapminder Dataset
# ============================================
# Load required libraries
library(gapminder)
library(dplyr)
library(ggplot2)
# Load the data
data("gapminder")
# View the first few rows
head(gapminder)
# ============================================
# Step 1: Explore the data
# ============================================
# Summary statistics by continent
gapminder %>%
group_by(continent) %>%
summarise(
n = n(),
mean_gdp = mean(gdpPercap),
sd_gdp = sd(gdpPercap),
median_gdp = median(gdpPercap)
)
# ============================================
# Step 2: Conduct One-way ANOVA
# ============================================
# Run ANOVA: GDP per capita by continent
anova_model <- aov(gdpPercap ~ continent, data = gapminder)
# View ANOVA summary
summary(anova_model)
# ============================================
# Step 3: Check Assumptions
# ============================================
# Diagnostic plots (normality and homoscedasticity)
par(mfrow = c(2, 2))
plot(anova_model)
par(mfrow = c(1, 1))
# Shapiro-Wilk test for normality of residuals (sample)
# Note: Using a sample as Shapiro-Wilk requires n < 5000
shapiro.test(sample(residuals(anova_model), 500))
# Levene's Test for homogeneity of variances
# install.packages("car") # Run if not installed
library(car)
leveneTest(gdpPercap ~ continent, data = gapminder)
# ============================================
# Step 4: Post-hoc Test (Tukey HSD)
# ============================================
# Run Tukey's Honest Significant Difference test
tukey_result <- TukeyHSD(anova_model)
# View results
print(tukey_result)
# ============================================
# Step 5: Visualise the Results
# ============================================
# Boxplot of GDP per capita by continent
ggplot(gapminder, aes(x = continent, y = gdpPercap, fill = continent)) +
geom_boxplot() +
labs(
title = "GDP per Capita by Continent",
x = "Continent",
y = "GDP per Capita (USD)"
) +
theme_minimal() +
theme(legend.position = "none")
# Boxplot with log-transformed GDP (better visualisation due to skewness)
ggplot(gapminder, aes(x = continent, y = gdpPercap, fill = continent)) +
geom_boxplot() +
scale_y_log10() +
labs(
title = "GDP per Capita by Continent (Log Scale)",
x = "Continent",
y = "GDP per Capita (USD, log scale)"
) +
theme_minimal() +
theme(legend.position = "none")
# Visualise Tukey HSD results
par(mar = c(5, 8, 4, 2))
plot(tukey_result, las = 1, cex.axis = 0.7)
# ============================================
# Interpretation Notes
# ============================================
# - If p-value < 0.05 in ANOVA summary: at least one continent differs significantly
# - Tukey results show pairwise comparisons:
#   - "diff" = difference in means
#   - "p adj" = adjusted p-value
#   - If confidence interval doesn't include 0, the difference is significant
