---
title: "Dummy Variables as Explanatory Regressors: Intercept Shifts, Interactions & Nested Testing"
subtitle: "Econometrics Exercise #9b"
author: "Ahmed Mustafa"
date: today
lang: en
format:
html:
toc: true
toc-location: left
toc-depth: 3
toc-title: "Contents"
number-sections: true
theme: cosmo
embed-resources: true
code-fold: true
code-summary: "Show R code"
code-tools: true
fig-align: center
fig-dpi: 150
execute:
echo: true
message: false
warning: false
---
```{css}
:root {
--brand: #AA272F;
--brand-dark: #7F1D24;
--brand-pale: #F7E9EA;
--brand-blue: #1B4F72;
--brand-green: #477A63;
--brand-amber: #B7791F;
--ink: #292929;
}
body { color: var(--ink); line-height: 1.6; }
h1, h2, h3 { color: var(--brand-dark); }
h1 { border-bottom: 2px solid var(--brand); padding-bottom: .25rem; margin-top: 2.4rem; }
h1.title { border-bottom: none; color: var(--brand); font-weight: 800; }
p.subtitle { color: var(--brand-blue); font-weight: 500; }
.callout-note { border-left-color: var(--brand) !important; }
.callout-tip { border-left-color: var(--brand-green) !important; }
.callout-warning { border-left-color: var(--brand-amber) !important; }
.callout-important { border-left-color: var(--brand-blue) !important; }
table caption { color: var(--brand-dark); font-weight: 700; }
table thead th { background: var(--brand-dark) !important; color: #fff !important; }
.table > tbody > tr:nth-of-type(odd) > * { background-color: #FBF5F5; }
/* Headline scorecards */
.stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
gap: .9rem; margin: 1.2rem 0 1.6rem; }
.stat-card { border: 1px solid #E7D3D5; border-top: 5px solid var(--brand); border-radius: 6px;
padding: .75rem 1rem .8rem; background: #fff; box-shadow: 0 2px 6px rgba(41,41,41,.07); }
.stat-card.blue { border-top-color: var(--brand-blue); }
.stat-card.green { border-top-color: var(--brand-green); }
.stat-card.amber { border-top-color: var(--brand-amber); }
.stat-label { font-size: .74rem; text-transform: uppercase; letter-spacing: .05em; color: #6b6b6b; font-weight: 700; }
.stat-value { font-size: 1.85rem; font-weight: 800; color: var(--brand-dark); line-height: 1.15; margin: .15rem 0 .2rem; }
.stat-note { font-size: .84rem; color: #444; line-height: 1.35; }
/* Reader legend */
.legend-row { display: flex; gap: .7rem; align-items: baseline; margin: .35rem 0; }
.chip { display: inline-block; min-width: 11.5rem; padding: .15rem .6rem; border-radius: 4px; color: #fff;
font-weight: 700; font-size: .85rem; text-align: center; }
.chip.tip { background: var(--brand-green); }
.chip.note { background: var(--brand); }
.chip.warn { background: var(--brand-amber); }
.chip.imp { background: var(--brand-blue); }
```
```{r}
#| label: setup
#| include: false
required_packages <- c("broom", "dplyr", "tidyr", "ggplot2", "knitr", "kableExtra",
"lmtest", "sandwich", "car", "patchwork", "scales")
missing_packages <- required_packages[
!vapply(required_packages, requireNamespace, logical(1), quietly = TRUE)]
if (length(missing_packages)) {
stop("Install these packages before rendering: ", paste(missing_packages, collapse = ", "))
}
library(dplyr)
library(tidyr)
library(ggplot2)
library(knitr)
library(kableExtra)
library(patchwork)
options(knitr.kable.NA = "–")
# ---- Brand identity (identical to Exercises 4, 5, 7, 8 and 9) --------------
brand <- "#AA272F"
brand_dark <- "#7F1D24"
brand_blue <- "#1B4F72"
brand_green <- "#477A63"
brand_amber <- "#B7791F"
brand_cols <- c(brand, brand_blue, brand_green, brand_amber, "#6C3483", "#5D6D7E")
brand_table <- function(x, caption, digits = 3, bold_rows = NULL) {
tb <- knitr::kable(x, format = "html", digits = digits, caption = caption,
row.names = FALSE, escape = TRUE) |>
kableExtra::kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE, position = "left") |>
kableExtra::row_spec(0, bold = TRUE, color = "white", background = brand_dark)
if (length(bold_rows)) tb <- kableExtra::row_spec(tb, bold_rows, bold = TRUE)
tb
}
theme_brand <- function(base_size = 12) {
theme_minimal(base_size = base_size) +
theme(plot.title = element_text(colour = brand_dark, face = "bold"),
plot.subtitle = element_text(colour = "#555555"),
strip.text = element_text(colour = brand_dark, face = "bold"),
panel.grid.minor = element_blank(),
legend.position = "bottom")
}
# ---- Formatting helpers (no dollar signs anywhere: they confuse Markdown maths) ----
fmt_p <- function(p) ifelse(is.na(p), "–", ifelse(p < 0.001, "< 0.001", sprintf("%.3f", p)))
ptxt <- function(p) ifelse(p < 0.001, "p < 0.001", paste0("p = ", sprintf("%.3f", p)))
f1 <- function(x) formatC(x, format = "f", digits = 1)
f2 <- function(x) formatC(x, format = "f", digits = 2)
f3 <- function(x) formatC(x, format = "f", digits = 3)
sgn <- function(x, d = 2) paste0(ifelse(x >= 0, "+", "−"), formatC(abs(x), format = "f", digits = d))
dirw <- function(x, up = "higher", down = "lower") ifelse(x >= 0, up, down)
stars <- function(p) as.character(cut(p, c(-Inf, .001, .01, .05, .1, Inf),
labels = c("***", "**", "*", ".", ""), right = FALSE))
evid <- function(p) ifelse(p < 0.01, "strong evidence",
ifelse(p < 0.05, "moderate evidence",
ifelse(p < 0.10, "only weak evidence", "no clear evidence")))
sig5 <- function(p) ifelse(p < 0.05, "statistically significant at 5%", "not statistically significant at 5%")
year_ranges <- function(y) {
y <- sort(unique(y))
if (!length(y)) return("none")
grp <- cumsum(c(1, diff(y) != 1))
paste(tapply(y, grp, function(v) if (length(v) == 1) as.character(v) else paste0(min(v), "–", max(v))),
collapse = ", ")
}
k10 <- log(1.10) # +10% GDP = +0.0953 on the log scale; used to translate slopes into everyday units
term_label <- function(x) {
x <- gsub("I(centr_logGDP * HighFDI)", "GDP × High-FDI (D1)", x, fixed = TRUE)
x <- gsub("centr_logGDP:HighFDI", "GDP × High-FDI (D1)", x, fixed = TRUE)
x <- gsub("centr_logGDP", "GDP, centred log", x, fixed = TRUE)
x <- gsub("HighFDI", "High-FDI year (D1)", x, fixed = TRUE)
x <- gsub("HighTrade", "High-trade year (D2)", x, fixed = TRUE)
x <- gsub("IndTier", "Industry tier: ", x, fixed = TRUE)
gsub("(Intercept)", "Intercept", x, fixed = TRUE)
}
# One-line "plain reading" of each coefficient (this is the interpretation column in every table)
reading <- function(term, est) {
a <- abs(est)
dplyr::case_when(
term == "(Intercept)" ~ sprintf("Predicted share ≈ %.1f%% for reference years at average GDP", est),
term == "centr_logGDP" ~ sprintf("%s pp of renewable share for every +10%% GDP", sgn(est * k10)),
grepl("centr_logGDP", term) & grepl("HighFDI", term) ~
sprintf("High-FDI slope differs by %s pp per +10%% GDP", sgn(est * k10)),
grepl("HighFDI|HighTrade|IndTier", term) ~
sprintf("%s pp vs reference years (at average GDP)", sgn(est)),
TRUE ~ "")
}
show_coef <- function(model, caption, digits = 3) {
td <- broom::tidy(model, conf.int = TRUE)
out <- data.frame(Term = term_label(td$term), Estimate = td$estimate, `Std. error` = td$std.error,
`t statistic` = td$statistic, `p-value` = fmt_p(td$p.value), `Sig.` = stars(td$p.value),
`95% CI` = sprintf("[%.2f, %.2f]", td$conf.low, td$conf.high),
`Plain reading` = reading(td$term, td$estimate), check.names = FALSE)
brand_table(out, caption, digits, bold_rows = which(td$p.value < 0.05))
}
ft <- function(restricted, unrestricted) {
a <- anova(restricted, unrestricted)
list(F = a$F[2], p = a$`Pr(>F)`[2], df1 = a$Df[2], df2 = a$Res.Df[2],
saved = a$`Sum of Sq`[2], rss_r = a$RSS[1], rss_u = a$RSS[2])
}
show_ftest <- function(restricted, unrestricted, caption) {
a <- anova(restricted, unrestricted)
p <- a$`Pr(>F)`[2]
out <- data.frame(
Model = c("Restricted (simpler)", "Unrestricted (richer)"),
`Res. df` = a$Res.Df, RSS = a$RSS, `Extra terms` = a$Df, `RSS saved` = a$`Sum of Sq`,
`F` = a$F, `p-value` = fmt_p(a$`Pr(>F)`),
Verdict = c("–", ifelse(p < 0.05, "The extra terms earn their place",
ifelse(p < 0.10, "Borderline", "No clear gain from the extra terms"))),
check.names = FALSE)
brand_table(out, caption, 3, bold_rows = if (p < 0.05) 2 else NULL)
}
hac_vcov <- function(x) sandwich::NeweyWest(x, prewhite = FALSE)
```
```{r}
#| label: load-data
#| include: false
# ---- 1. Restore the saved workspace (falls back to the CSV only if it is missing) ------
read_sudan_csv <- function() {
csv <- c("udaje/LDC-Panel-Data.csv", "LDC-Panel-Data.csv")
csv <- csv[file.exists(csv)]
if (!length(csv)) return(NULL)
raw <- read.csv(csv[1], na.strings = c("", "NA"), stringsAsFactors = FALSE,
fileEncoding = "UTF-8-BOM")
list(path = csv[1],
data = raw |> dplyr::filter(Country_Code == "SDN") |>
dplyr::mutate(logGDP = log(GDP_USD / 1e9)) |> dplyr::arrange(Year))
}
req <- c("REN_ERG_CONS", "logGDP", "FDI_GDP", "Trade_GDP", "IND_VA_GDP")
ws_file <- "pamat_cvicenie9.Rdata"
ws_env <- new.env(parent = baseenv())
if (file.exists(ws_file)) load(ws_file, envir = ws_env)
if (exists("udaje9", envir = ws_env, inherits = FALSE)) {
raw_df <- get("udaje9", envir = ws_env)
data_source <- paste0(ws_file, " (object: udaje9)")
} else {
csv_in <- read_sudan_csv()
if (is.null(csv_in)) stop("Neither pamat_cvicenie9.Rdata nor LDC-Panel-Data.csv was found in the working directory.")
raw_df <- csv_in$data
data_source <- paste0(csv_in$path, " (Sudan rows only)")
}
stopifnot(all(req %in% names(raw_df)))
# ---- 2. The Exercise 9 workspace does not store Year: restore or infer it, and say so --
year_note <- "Year column found in the workspace"
if (!"Year" %in% names(raw_df)) {
csv_in <- read_sudan_csv()
cc <- if (!is.null(csv_in)) dplyr::filter(csv_in$data, dplyr::if_all(dplyr::all_of(req), is.finite)) else NULL
if (!is.null(cc) && nrow(cc) == nrow(raw_df) &&
isTRUE(all.equal(cc$REN_ERG_CONS, raw_df$REN_ERG_CONS, check.attributes = FALSE))) {
raw_df$Year <- cc$Year
year_note <- "Year restored from LDC-Panel-Data.csv (rows matched one-to-one)"
} else if (nrow(raw_df) == 27) {
raw_df$Year <- 1995:2021
year_note <- "Year is not stored in the workspace: assumed 1995–2021 (27 consecutive complete years)"
} else {
raw_df$Year <- seq_len(nrow(raw_df))
year_note <- "Year is not available: observation number used instead"
}
}
df_clean <- raw_df |>
dplyr::select(dplyr::all_of(c("Year", req))) |>
dplyr::filter(dplyr::if_all(dplyr::everything(), ~ is.finite(.x))) |>
dplyr::arrange(Year) |>
as.data.frame()
N_obs <- nrow(df_clean)
stopifnot(N_obs > 15, !anyDuplicated(df_clean$Year))
year_lo <- min(df_clean$Year); year_hi <- max(df_clean$Year)
# ---- 3. Build the regimes (dummies) and centre GDP --------------------------------------
med_fdi <- median(df_clean$FDI_GDP)
med_trade <- median(df_clean$Trade_GDP)
tertiles_ind <- quantile(df_clean$IND_VA_GDP, probs = c(1/3, 2/3), names = FALSE)
stopifnot(tertiles_ind[1] < tertiles_ind[2])
mean_lgdp <- mean(df_clean$logGDP)
df_clean <- df_clean |>
dplyr::mutate(
GDP_bn = exp(logGDP),
centr_logGDP = logGDP - mean_lgdp,
HighFDI = as.integer(FDI_GDP > med_fdi),
HighTrade = as.integer(Trade_GDP > med_trade),
FDI_Group = factor(HighFDI, levels = 0:1, labels = c("Low-FDI year", "High-FDI year")),
Trade_Group = factor(HighTrade, levels = 0:1, labels = c("Low-trade year", "High-trade year")),
IndTier = cut(IND_VA_GDP, breaks = c(-Inf, tertiles_ind, Inf),
labels = c("Low", "Medium", "High"), right = TRUE))
stopifnot(nlevels(droplevels(df_clean$FDI_Group)) == 2)
mean_gdp_bn <- exp(mean_lgdp)
# ---- 4. The six models (same names as before, so Exercise 10 keeps working) -------------
m_base <- lm(REN_ERG_CONS ~ centr_logGDP, data = df_clean)
m_int <- lm(REN_ERG_CONS ~ centr_logGDP + HighFDI, data = df_clean)
m_slope <- lm(REN_ERG_CONS ~ centr_logGDP + I(centr_logGDP * HighFDI), data = df_clean)
m_inter <- lm(REN_ERG_CONS ~ centr_logGDP * HighFDI, data = df_clean)
m_dual <- lm(REN_ERG_CONS ~ centr_logGDP + HighFDI + HighTrade, data = df_clean)
m_poly <- lm(REN_ERG_CONS ~ centr_logGDP + IndTier, data = df_clean)
# Same models WITHOUT centring: used only to show why centring is needed
m_inter_raw <- lm(REN_ERG_CONS ~ logGDP * HighFDI, data = df_clean)
m_slope_raw <- lm(REN_ERG_CONS ~ logGDP + I(logGDP * HighFDI), data = df_clean)
models <- list(
"M1 One common line" = m_base,
"M2 Parallel lines (level shifts)" = m_int,
"M3 Same start, different tilt" = m_slope,
"M4 Level and tilt (interaction)" = m_inter,
"M5 Two dummies (FDI + trade)" = m_dual,
"M6 Three industry tiers" = m_poly)
short_nm <- sub(" .*", "", names(models))
# ---- 5. Headline numbers reused in the summary and later sections ------------------------
raw_fit <- lm(REN_ERG_CONS ~ HighFDI, data = df_clean)
gap_raw <- unname(coef(raw_fit)["HighFDI"]); p_gap_raw <- summary(raw_fit)$coefficients["HighFDI", 4]
gap_ctrl <- unname(coef(m_int)["HighFDI"]); p_gap_ctrl <- summary(m_int)$coefficients["HighFDI", 4]
f_int <- ft(m_base, m_int); f_slope_only <- ft(m_base, m_slope)
f_slope_inc <- ft(m_int, m_inter); f_chow <- ft(m_base, m_inter)
f_d2 <- ft(m_int, m_dual); f_tier <- ft(m_base, m_poly)
# Exact OLS identity: raw gap = gap at equal GDP + (slope x average GDP head-start of High-FDI years)
dz <- mean(df_clean$centr_logGDP[df_clean$HighFDI == 1]) - mean(df_clean$centr_logGDP[df_clean$HighFDI == 0])
pull <- unname(coef(m_int)["centr_logGDP"]) * dz
stopifnot(isTRUE(all.equal(gap_ctrl + pull, gap_raw, tolerance = 1e-6)))
rich_w <- ifelse(dz >= 0, "richer", "poorer"); gdp_dir <- ifelse(dz >= 0, "higher", "lower")
why_raw <- if (sign(pull) != sign(gap_ctrl)) {
sprintf("Raw averages hide part of the gap because High-FDI years were also %s years (about %.1f%% %s GDP on average), and that GDP difference alone moves the renewable share by %s pp, which cancels part of the FDI gap.",
rich_w, 100 * abs(exp(dz) - 1), gdp_dir, sgn(pull))
} else {
sprintf("Part of the raw gap is simply a GDP difference: High-FDI years had about %.1f%% %s GDP on average, which is worth %s pp.",
100 * abs(exp(dz) - 1), gdp_dir, sgn(pull))
}
m2_plain <- paste0(why_raw, " Comparing years of equal GDP removes this: the gap moves from ",
f2(abs(gap_raw)), " to ", f2(abs(gap_ctrl)), " pp.")
glance_all <- dplyr::bind_rows(lapply(names(models), function(n) {
g <- broom::glance(models[[n]])
data.frame(Model = n, k = length(coef(models[[n]])), R2 = g$r.squared, adjR2 = g$adj.r.squared,
sigma = g$sigma, AIC = g$AIC, BIC = g$BIC)
}))
best_i <- which.min(glance_all$BIC)
best_name <- glance_all$Model[best_i]; best_short <- short_nm[best_i]; best_m <- models[[best_i]]
best_aic_i <- which.min(glance_all$AIC)
glance_all$dBIC <- glance_all$BIC - min(glance_all$BIC)
glance_all$dAIC <- glance_all$AIC - min(glance_all$AIC)
# ---- 6. Stress tests: serial correlation, HAC robustness, cut-off sensitivity -------------
dw_tab <- dplyr::bind_rows(lapply(names(models), function(n) {
m <- models[[n]]; d1 <- lmtest::dwtest(m); b2 <- lmtest::bgtest(m, order = 2)
data.frame(Model = n, DW = unname(d1$statistic), p_DW = d1$p.value, p_BG = b2$p.value)
}))
hac_p <- function(m, term) lmtest::coeftest(m, vcov. = hac_vcov(m))[term, 4]
hac_j <- function(r, u) lmtest::waldtest(r, u, vcov = hac_vcov)$`Pr(>F)`[2]
cl_p <- function(m, term) summary(m)$coefficients[term, 4]
hac_tab <- data.frame(
Question = c("M2: do High-FDI years sit at a different level (same GDP)?",
"M4: does the GDP slope differ between regimes?",
"M4: are the two regime lines identical (level and tilt)?",
"M5: High-FDI gap, once trade regime is controlled",
"M5: High-trade gap, once FDI regime is controlled",
"M6: do the industry tiers matter (jointly)?"),
Estimate = c(coef(m_int)["HighFDI"], coef(m_inter)["centr_logGDP:HighFDI"] * k10, NA,
coef(m_dual)["HighFDI"], coef(m_dual)["HighTrade"], NA),
p_classic = c(cl_p(m_int, "HighFDI"), cl_p(m_inter, "centr_logGDP:HighFDI"), f_chow$p,
cl_p(m_dual, "HighFDI"), cl_p(m_dual, "HighTrade"), f_tier$p),
p_hac = c(hac_p(m_int, "HighFDI"), hac_p(m_inter, "centr_logGDP:HighFDI"), hac_j(m_base, m_inter),
hac_p(m_dual, "HighFDI"), hac_p(m_dual, "HighTrade"), hac_j(m_base, m_poly)),
row.names = NULL)
cut_grid <- seq(0.30, 0.70, by = 0.025)
sens <- do.call(rbind, lapply(cut_grid, function(q) {
cutv <- quantile(df_clean$FDI_GDP, q, names = FALSE)
d <- transform(df_clean, D = as.integer(FDI_GDP > cutv))
if (min(table(d$D)) < 4 || length(unique(d$D)) < 2) return(NULL)
m_d <- lm(REN_ERG_CONS ~ centr_logGDP + D, data = d)
m_i <- lm(REN_ERG_CONS ~ centr_logGDP * D, data = d)
ci <- confint(m_d)["D", ]
data.frame(q = q, cut = cutv, n_high = sum(d$D), gap = unname(coef(m_d)["D"]), lo = ci[[1]], hi = ci[[2]],
p_gap = summary(m_d)$coefficients["D", 4], p_joint = anova(m_base, m_i)$`Pr(>F)`[2])
}))
# headline strings used by the 60-second summary
strength <- function(pc, ph) ifelse(pc < 0.05 & ph < 0.05, "Robust",
ifelse(pmin(pc, ph) < 0.05, "Fragile",
ifelse(pmin(pc, ph) < 0.10, "Weak", "No clear evidence")))
hac_tab$Strength <- strength(hac_tab$p_classic, hac_tab$p_hac)
i_fdi <- 1; i_slope <- 2; i_joint <- 3; i_fdi5 <- 4; i_trade5 <- 5; i_tier <- 6
n_sens_sig <- sum(sens$p_gap < 0.05); n_sens <- nrow(sens)
dw_best <- dw_tab$DW[best_i]
```
# 60-second version {.unnumbered}
```{r}
#| label: scorecards
#| results: asis
#| echo: false
card <- function(label, value, note, tone = "") {
sprintf('<div class="stat-card %s"><div class="stat-label">%s</div><div class="stat-value">%s</div><div class="stat-note">%s</div></div>',
tone, label, value, note)
}
cards <- c(
card("Raw gap in averages", paste0(sgn(gap_raw), " pp"),
paste0("High-FDI vs Low-FDI years, no controls (", ptxt(p_gap_raw), ")")),
card("Gap at the same GDP", paste0(sgn(gap_ctrl), " pp"),
paste0("Model 2 dummy: High-FDI years vs Low-FDI years of equal GDP (", ptxt(p_gap_ctrl), ")"), "blue"),
card("Do GDP slopes differ?", ptxt(f_slope_inc$p),
paste0("Model 4 extra-slope test: ", evid(f_slope_inc$p), " that the GDP effect changes with the FDI regime"), "amber"),
card("Best-fitting model", best_short,
paste0(sub("^M[0-9] ", "", best_name), " (lowest BIC; adjusted R² = ", f2(glance_all$adjR2[best_i]), ")"), "green"))
cat("```{=html}\n<div class=\"stat-grid\">", paste(cards, collapse = ""), "</div>\n```\n", sep = "")
```
```{r}
#| label: summary-text
#| include: false
b_trade5 <- unname(coef(m_dual)["HighTrade"]); b_fdi5 <- unname(coef(m_dual)["HighFDI"])
p_trade5 <- summary(m_dual)$coefficients["HighTrade", 4]; p_fdi5 <- summary(m_dual)$coefficients["HighFDI", 4]
trade_ok <- hac_tab$Strength[i_trade5] == "Robust"
txt_raw <- if (abs(gap_raw) < 1) "practically no difference" else "a modest difference"
txt_slope <- if (f_slope_inc$p >= 0.05) "do not clearly change how GDP matters" else "change how GDP matters"
txt_trade <- if (p_trade5 < p_fdi5) "Trade openness matters more." else "Trade openness matters less."
txt_best <- if (best_short == "M5") "gives the best-fitting model (M5)" else paste0("the best-fitting model is ", best_short)
```
::: {.callout-tip}
## Summary
- **Raw averages.** Years with above-median FDI had a renewable share only `r f2(abs(gap_raw))` percentage points (pp) `r dirw(gap_raw)` than other years (`r ptxt(p_gap_raw)`): `r txt_raw`.
- **Holding GDP fixed changes the picture.** Comparing years of the *same* GDP, High-FDI years sit `r f2(abs(gap_ctrl))` pp `r dirw(gap_ctrl)` (`r ptxt(p_gap_ctrl)`, `r evid(p_gap_ctrl)`). `r why_raw`
- **FDI regimes `r txt_slope`.** The test that the two regimes have different GDP slopes gives `r ptxt(f_slope_inc$p)` (`r evid(f_slope_inc$p)`).
- **`r txt_trade`** Adding a High-trade dummy puts High-trade years `r f2(abs(b_trade5))` pp `r dirw(b_trade5)` (`r ptxt(p_trade5)`), changes the FDI gap to `r f2(abs(b_fdi5))` pp (`r ptxt(p_fdi5)`), and `r txt_best`.
- **How far to trust it:** `r if (trade_ok) "the trade-regime result survives a robustness check for autocorrelated errors, and" else "even the trade-regime result is sensitive to the error assumptions, and"` the FDI-regime result is rated **"`r tolower(hac_tab$Strength[i_fdi])`"** (see @sec-stress). All results are associations in `r N_obs` annual observations, not causal effects.
:::
# How to read this document
::: {.callout-important}
## Four kinds of boxes, one idea each
```{=html}
<div class="legend-row"><span class="chip tip">In Simple Terms</span><span>The idea in in simple terms.</span></div>
<div class="legend-row"><span class="chip note">What the numbers say</span><span>Every number in the table above it, translated into units you can picture.</span></div>
<div class="legend-row"><span class="chip warn">Careful</span><span>Why the number might mislead you.</span></div>
<div class="legend-row"><span class="chip imp">Verdict</span><span>The decision, in one or two sentences.</span></div>
```
**pp** means *percentage points of renewable share* (for example, going from 60% to 63% is +3 pp). Rows in **bold** in a coefficient table have p < 0.05.
:::
| Term | Meaning |
|:-----------------------|:------------------------------------------------------------------|
| **Dummy variable** | A yes/no switch: 1 for the years in a group, 0 for all other years |
| **Reference group** | The group the switch is compared against (here the Low-FDI years) |
| **Level shift (intercept shift)** | The whole line moves up or down |
| **Tilt (slope shift, interaction)** | The line rotates: GDP matters differently in the two groups |
| **Nested models and F-test** | A simple model vs the same model plus extra terms. The F-test asks: *did the extras earn their place?* |
| **AIC, BIC** | Fit scores that charge a fee for every extra term. Lower is better. BIC charges more |
| **HAC standard errors** | An honest margin of error for data where each year resembles the previous year |
::: {.callout-warning}
## Ground rules that apply to every result below
- **Association, not causation.** The groups are drawn by the analyst from Sudan's own sample (a median split, not an official classification, and not a randomised treatment).
- **One country, `r N_obs` annual observations (`r year_lo`–`r year_hi`).** Small samples give tests low power: "not significant" never means "no effect".
- **Years are not independent.** @sec-stress checks what this does to the p-values.
- **Course convention:** the matrix of regressors is treated as fixed (deterministic).
:::
# Meet the data
## The sample
```{r}
#| label: sample-table
data.frame(
Item = c("Country", "Workspace source", "Period", "Complete annual observations (N)",
"Outcome (y)", "Regressor", "Year information"),
Value = c("Sudan (SDN)", data_source, paste(year_lo, year_hi, sep = "–"), N_obs,
"REN_ERG_CONS: renewable energy, % of final energy consumption",
"logGDP: natural log of GDP in billion USD, centred (see Step 0 below)", year_note)
) |> brand_table("Sample used in every model of this exercise")
```
::: {.callout-note}
## What the numbers say
All six models use exactly the same `r N_obs` years, so their F-tests and their AIC/BIC scores are comparable. Sudan's GDP in this sample runs from about USD `r f1(min(df_clean$GDP_bn))` bn to USD `r f1(max(df_clean$GDP_bn))` bn, with a typical (geometric-mean) value of about USD `r f1(mean_gdp_bn)` bn. The renewable share starts at `r f1(df_clean$REN_ERG_CONS[1])`% in `r year_lo` and ends at `r f1(df_clean$REN_ERG_CONS[N_obs])`% in `r year_hi`.
:::
## The dummy-variable toolbox in one picture
::: {.callout-tip}
## In Simple Terms
A dummy variable lets two groups of years share one regression but follow **their own rules**. There are four possible categories. The six models in this document are simply ways of asking which category Sudan belongs to. (The lines below are an illustration, not Sudan's data.)
:::
```{r}
#| label: fig-toolbox
#| fig-cap: "The four possible categories for two groups of years (illustration only)."
#| fig-width: 10
#| fig-height: 3.6
x <- seq(-1, 1, length.out = 40)
mk <- function(panel, f_low, f_high) {
rbind(data.frame(panel = panel, x = x, y = f_low(x), grp = "Low-FDI years"),
data.frame(panel = panel, x = x, y = f_high(x), grp = "High-FDI years"))
}
toy <- rbind(
mk("A. One common line\n(regime does not matter)", function(x) -x, function(x) -x),
mk("B. Parallel lines\n(level shifts)", function(x) -x, function(x) -x + 0.9),
mk("C. Same start, new tilt\n(slope shifts)", function(x) -x, function(x) -0.2 * x),
mk("D. Level and tilt differ\n(full interaction)", function(x) -x, function(x) 0.6 - 0.2 * x))
toy$panel <- factor(toy$panel, levels = unique(toy$panel))
ggplot(toy, aes(x, y, colour = grp, linetype = grp, linewidth = grp)) +
geom_line() +
facet_wrap(~ panel, nrow = 1) +
scale_colour_manual(values = c("Low-FDI years" = brand_blue, "High-FDI years" = brand), name = NULL) +
scale_linetype_manual(values = c("Low-FDI years" = "solid", "High-FDI years" = "22"), name = NULL) +
scale_linewidth_manual(values = c("Low-FDI years" = 1.8, "High-FDI years" = 1.0), name = NULL) +
labs(x = "GDP →", y = "Renewable share →") +
theme_brand() +
theme(axis.text = element_blank(), panel.grid = element_blank())
```
| Model | The question it asks | Category |
|:---|:---------------------------------------------------------------|:--:|
| **M1** | Is one common line enough for all years? | A |
| **M2** | At the same GDP, do High-FDI years sit higher or lower? | B |
| **M3** | Do the two lines share a starting point but tilt differently? | C |
| **M4** | Can both level and tilt differ? | D |
| **M5** | Does a second switch (trade openness) add anything beyond FDI? | B (two switches) |
| **M6** | Does industry's share of GDP (three groups) shift the line? | B (three groups) |
## How Sudan's years are split into regimes {#sec-regimes}
```{r}
#| label: tbl-thresholds
tier_n <- table(df_clean$IndTier)
thr <- data.frame(
`Dummy` = c("D1: High-FDI year", "D2: High-trade year", "Industry tier: Medium", "Industry tier: High"),
`Rule (a year counts as 1 when ...)` = c(
paste0("FDI_GDP > ", f2(med_fdi), " % of GDP (sample median; a tie counts as Low)"),
paste0("Trade_GDP > ", f2(med_trade), " % of GDP (sample median)"),
paste0(f2(tertiles_ind[1]), " < IND_VA_GDP ≤ ", f2(tertiles_ind[2]), " % of GDP (middle third)"),
paste0("IND_VA_GDP > ", f2(tertiles_ind[2]), " % of GDP (top third)")),
`Reference group` = c("Low-FDI years", "Low-trade years", "Low-industry years", "Low-industry years"),
`Years coded 0 / 1` = c(
paste(table(df_clean$HighFDI), collapse = " / "), paste(table(df_clean$HighTrade), collapse = " / "),
paste(nrow(df_clean) - tier_n[["Medium"]], "/", tier_n[["Medium"]]),
paste(nrow(df_clean) - tier_n[["High"]], "/", tier_n[["High"]])),
`Which years` = c(year_ranges(df_clean$Year[df_clean$HighFDI == 1]),
year_ranges(df_clean$Year[df_clean$HighTrade == 1]),
year_ranges(df_clean$Year[df_clean$IndTier == "Medium"]),
year_ranges(df_clean$Year[df_clean$IndTier == "High"])),
check.names = FALSE)
brand_table(thr, "How the regimes are defined, and which years fall into each")
```
```{r}
#| label: fig-timeline
#| fig-cap: "Sudan's renewable share (top) and FDI inflows (bottom). Colour shows the FDI regime; the dashed line is the median that defines it."
#| fig-width: 9
#| fig-height: 6
pal_fdi <- c("Low-FDI year" = brand_blue, "High-FDI year" = brand)
p_a <- ggplot(df_clean, aes(Year, REN_ERG_CONS)) +
geom_line(colour = "grey75") +
geom_point(aes(colour = FDI_Group), size = 3) +
scale_colour_manual(values = pal_fdi, name = NULL) +
labs(title = "Renewable share of energy use", x = NULL, y = "% of final energy") + theme_brand()
p_b <- ggplot(df_clean, aes(Year, FDI_GDP, fill = FDI_Group)) +
geom_col(width = 0.75) +
geom_hline(yintercept = med_fdi, linetype = "dashed", colour = brand_dark) +
annotate("text", x = year_lo, y = med_fdi, label = paste0("median = ", f2(med_fdi), "% of GDP"),
vjust = -0.7, hjust = 0, size = 3.5, colour = brand_dark) +
scale_fill_manual(values = pal_fdi, name = NULL) +
labs(title = "FDI net inflows", x = "Year", y = "% of GDP") + theme_brand()
(p_a / p_b) + plot_layout(guides = "collect") & theme(legend.position = "bottom")
r_h_year <- cor(df_clean$HighFDI, df_clean$Year)
r_ren_year <- cor(df_clean$REN_ERG_CONS, df_clean$Year)
r_z_year <- cor(df_clean$centr_logGDP, df_clean$Year)
```
::: {.callout-note}
## What the numbers say
- High-FDI years are **scattered through time**, not one early or late block (correlation between the dummy and the calendar year is only `r f2(r_h_year)`). The regimes are interleaved, so this is not simply "before vs after".
- Time, however, matters a lot: the renewable share has a correlation of `r f2(r_ren_year)` with the calendar year, and log GDP has `r f2(r_z_year)`. Both drift through time, which will matter when we interpret the GDP slope.
:::
::: {.callout-warning}
## Careful: the cut-off is a choice
Splitting at the median is convenient, but the 40th or the 60th percentile could also be used. @sec-cutoffs re-runs the key result for 17 different cut-offs to see whether the story depends on this choice.
:::
# First look: raw averages, no controls {#sec-first-look}
```{r}
#| label: fig-box
#| fig-cap: "Renewable share by FDI regime. Boxes show median and quartiles, dots are years, diamonds are group means."
#| fig-width: 8.5
#| fig-height: 4.5
means_d1 <- df_clean |> group_by(FDI_Group) |> summarise(m = mean(REN_ERG_CONS), n = n(), .groups = "drop")
ggplot(df_clean, aes(FDI_Group, REN_ERG_CONS, colour = FDI_Group, fill = FDI_Group)) +
geom_boxplot(width = 0.4, alpha = 0.15, outlier.shape = NA, linewidth = 0.8) +
geom_jitter(width = 0.1, size = 2.6, alpha = 0.8) +
geom_point(data = means_d1, aes(y = m), shape = 18, size = 5.5, colour = "#292929") +
geom_text(data = means_d1, aes(y = m, label = paste0("mean ", f1(m), "% (n = ", n, ")")),
nudge_x = 0.36, fontface = "bold", size = 3.6, colour = "#292929") +
scale_colour_manual(values = pal_fdi) + scale_fill_manual(values = pal_fdi) +
labs(x = NULL, y = "Renewable share (% of final energy)") +
theme_brand() + theme(legend.position = "none")
```
::: {.callout-note}
## What the numbers say
The two group averages differ by **`r f2(abs(gap_raw))` pp** (`r dirw(gap_raw, "High-FDI years higher", "High-FDI years lower")`; `r ptxt(p_gap_raw)`, `r evid(p_gap_raw)`). Across all years the renewable share ranges over roughly `r f1(diff(range(df_clean$REN_ERG_CONS)))` pp, so a `r f2(abs(gap_raw))` pp gap is a rounding error by comparison. (This gap is mathematically identical to the coefficient of a regression of the renewable share on the dummy alone.)
:::
::: {.callout-tip}
## In Simple Terms
At first glance the FDI regime seems irrelevant. But averages ignore that the two groups differ in **other ways**, above all in GDP. The six models below compare years *at equal GDP*, which is a fairer comparison.
:::
# The six models, one question at a time
## Step 0: put GDP on a human scale (centring) {#sec-centring}
```{r}
#| label: centring
rungs <- c(min(df_clean$GDP_bn), mean_gdp_bn, max(df_clean$GDP_bn))
data.frame(
`GDP level` = c("Smallest in sample", "Typical (centre)", "Largest in sample"),
`GDP (billion USD)` = rungs,
`log GDP` = log(rungs),
`Centred value used in the models` = log(rungs) - mean_lgdp,
check.names = FALSE) |>
brand_table("Centred log GDP: zero means 'Sudan at its typical GDP'", 2)
gap_unc <- unname(coef(m_inter_raw)["HighFDI"]); int_unc <- unname(coef(m_inter_raw)["(Intercept)"])
```
::: {.callout-tip}
## In Simple Terms
Models use the centred variable $z_t=\ln GDP_t-\overline{\ln GDP}$. Zero now means "Sudan at its typical GDP (about USD `r f1(mean_gdp_bn)` bn)". Because $+10\%$ GDP equals $+0.095$ on this scale, every GDP slope below is reported as **"pp per +10% GDP"**, which is a change you can picture.
:::
::: {.callout-warning}
## Careful: Centring the dummy is necessary
If GDP is not centred, the intercept and the dummy describe Sudan at **log GDP = 0, i.e. a GDP of USD 1 bn**, a size Sudan never had (the smallest observed is USD `r f1(min(df_clean$GDP_bn))` bn). Estimated that way, the intercept would be **`r f1(int_unc)`%** of renewable energy (`r if (int_unc > 100) "impossible: above 100%" else "far outside the sample"`) and the High-FDI "level shift" would be **`r f1(gap_unc)` pp**. Centring changes none of the fitted lines (the fit is identical) but makes every coefficient describe a *real* Sudan. The joint F-tests are unaffected as well.
:::
## Model 1: one common line (the benchmark)
*Question: if the FDI regime is ignored, how does the renewable share move with GDP?*
$$REN_t=\beta_0+\beta_1\,z_t+u_t$$
```{r}
#| label: m1
show_coef(m_base, "Model 1: one line for all years", 3)
s1 <- summary(m_base)
n1 <- list(int = unname(coef(m_base)[1]), slope10 = unname(coef(m_base)[2]) * k10,
p = s1$coefficients[2, 4], adj = s1$adj.r.squared, sigma = s1$sigma)
```
::: {.callout-note}
## What the numbers say
- **Intercept ≈ `r f1(n1$int)`%:** at Sudan's typical GDP, the model predicts a renewable share of about `r f1(n1$int)`%.
- **Slope:** every **+10% GDP** goes with **`r sgn(n1$slope10)` pp** of renewable share (`r ptxt(n1$p)`).
- **Fit:** adjusted $R^2$ = `r f2(n1$adj)`, so GDP alone accounts for about **`r f1(100 * n1$adj)`%** of the year-to-year variation. A typical year is missed by about **`r f1(n1$sigma)` pp**.
:::
::: {.callout-warning}
## Careful: two things drifting through time
Both the renewable share and GDP trend through the calendar (correlations with year: `r f2(r_ren_year)` and `r f2(r_z_year)`). A strong slope can therefore reflect "two series moving through time" and not "GDP growth lowers renewables". Remember this for every model that follows.
:::
## Model 2: parallel lines, a level shift
*Question: at the **same GDP**, do High-FDI years sit higher or lower than Low-FDI years?*
$$REN_t=\beta_0+\beta_1\,z_t+\beta_2\,D_{1t}+u_t \qquad H_0:\ \beta_2=0$$
```{r}
#| label: m2
show_coef(m_int, "Model 2: parallel lines (intercept shift for High-FDI years)", 3)
show_ftest(m_base, m_int, "Does adding the High-FDI dummy help? Partial F-test (Model 1 vs Model 2)")
ci2 <- confint(m_int)["HighFDI", ]
```
::: {.callout-note}
## What the numbers say
- **The dummy (β₂):** at the same GDP, High-FDI years have a renewable share **`r f2(abs(gap_ctrl))` pp `r dirw(gap_ctrl)`** than Low-FDI years. The 95% interval runs from `r sgn(ci2[[1]])` to `r sgn(ci2[[2]])` pp: `r if (ci2[[1]] * ci2[[2]] > 0) "it excludes zero" else "it includes zero"`, so the data show **`r evid(p_gap_ctrl)`** (`r ptxt(p_gap_ctrl)`) of a gap.
- **F-test:** adding the dummy `r if (f_int$p < 0.05) "reduces the unexplained variation by" else "would reduce it by only"` `r f1(100 * f_int$saved / f_int$rss_r)`% (F = `r f2(f_int$F)`, `r ptxt(f_int$p)`). With one extra term, this F-test is equivalent to the dummy's own t-test.
- **The slope is unchanged in spirit:** every +10% GDP still goes with about `r sgn(coef(m_int)["centr_logGDP"] * k10)` pp in *both* regimes: parallel lines have a common tilt by construction.
:::
```{r}
#| label: m2-decomposition
data.frame(
Piece = c("Gap at the same GDP (the Model 2 dummy)",
"GDP head-start of High-FDI years × GDP slope",
"= Raw gap in simple averages (the boxplot above)"),
`pp of renewable share` = c(gap_ctrl, pull, gap_raw),
`How to read it` = c(
"High-FDI vs Low-FDI years that have identical GDP",
sprintf("High-FDI years had %.1f%% %s GDP on average, and GDP goes with %s pp per +10%%",
100 * abs(exp(dz) - 1), ifelse(dz >= 0, "more", "less"), sgn(coef(m_int)["centr_logGDP"] * k10)),
"What a naive comparison of averages shows"),
check.names = FALSE) |>
brand_table("Why the raw gap and the same-GDP gap differ (an exact accounting identity)", 2)
```
::: {.callout-tip}
## In Simple Terms
The raw gap is the sum of two ingredients: the true same-GDP gap and a GDP "head-start" effect. `r m2_plain` The model *removes* the head-start by comparing like with like.
:::
```{r}
#| label: fig-m2
#| fig-cap: "Model 2: two parallel lines with 95% confidence bands for the mean. Labels are years."
#| fig-width: 8.5
#| fig-height: 5
grid_z <- seq(min(df_clean$centr_logGDP), max(df_clean$centr_logGDP), length.out = 100)
pred_for <- function(model, extra = NULL) {
g <- expand.grid(centr_logGDP = grid_z, HighFDI = c(0, 1))
if (!is.null(extra)) g <- cbind(g, extra)
p <- cbind(g, predict(model, newdata = g, interval = "confidence"))
p$FDI_Group <- factor(p$HighFDI, levels = 0:1, labels = levels(df_clean$FDI_Group))
p$GDP_bn <- exp(p$centr_logGDP + mean_lgdp)
p
}
regime_plot <- function(pred, title, subtitle, show_y = TRUE) {
ggplot() +
geom_ribbon(data = pred, aes(GDP_bn, ymin = lwr, ymax = upr, fill = FDI_Group), alpha = 0.15) +
geom_line(data = pred, aes(GDP_bn, fit, colour = FDI_Group), linewidth = 1.2) +
geom_point(data = df_clean, aes(GDP_bn, REN_ERG_CONS, colour = FDI_Group), size = 2.4, alpha = 0.85) +
geom_text(data = df_clean, aes(GDP_bn, REN_ERG_CONS, label = sprintf("'%02d", Year %% 100), colour = FDI_Group),
size = 2.7, vjust = -1, check_overlap = TRUE, show.legend = FALSE) +
scale_x_log10(breaks = c(25, 30, 40, 50, 60)) +
scale_colour_manual(values = pal_fdi, name = NULL) + scale_fill_manual(values = pal_fdi, name = NULL) +
labs(title = title, subtitle = subtitle, x = "GDP (billion USD, log scale)",
y = if (show_y) "Renewable share (% of final energy)" else NULL) +
theme_brand()
}
pred_int <- pred_for(m_int)
regime_plot(pred_int, "Model 2: parallel lines",
paste0("Vertical gap between the lines = ", sgn(gap_ctrl), " pp at every GDP level"))
```
::: {.callout-note}
## What the picture says
The two lines fall from left to right (more GDP, lower renewable share). The red line sits `r f2(abs(gap_ctrl))` pp `r dirw(gap_ctrl, "above", "below")` the blue line everywhere. The shaded bands overlap `r if (p_gap_ctrl < 0.05) "only partly" else "heavily"`, which is the picture version of "`r evid(p_gap_ctrl)`".
:::
## Model 3: same start, different tilt
*Question: do the lines meet at one point but tilt differently?*
$$REN_t=\beta_0+\beta_1\,z_t+\beta_2\,(z_t\cdot D_{1t})+u_t$$
```{r}
#| label: m3
show_coef(m_slope, "Model 3: common intercept, slope shift only", 3)
show_ftest(m_base, m_slope, "Partial F-test: Model 1 vs Model 3")
aic_cen <- AIC(m_slope); aic_raw <- AIC(m_slope_raw)
```
::: {.callout-note}
## What the numbers say
The tilt difference is **`r sgn(coef(m_slope)[3] * k10)` pp per +10% GDP** (`r ptxt(summary(m_slope)$coefficients[3, 4])`), so the tilt is **`r sig5(f_slope_only$p)`**. With a single extra term the F-test and this t-test are the same test.
:::
::: {.callout-warning}
## Careful: Model 3 depends on where you place the origin
Forcing both lines through the same point means "the regimes are identical at zero". With centred GDP that point is Sudan's typical GDP; with uncentred GDP it is USD 1 bn. The same type of model then fits differently: **AIC = `r f2(aic_cen)` (centred) vs `r f2(aic_raw)` (uncentred)**, a difference of `r f2(abs(aic_cen - aic_raw))` units caused only by an arbitrary choice of origin. A result that changes when you shift the axis is not a finding about Sudan. That it is recommended to **keep the main effect (the dummy) whenever an interaction is in the model**, which is exactly Model 4.
:::
## Model 4: level and tilt can both differ
*Question: do the two regimes follow different lines altogether?*
$$REN_t=\beta_0+\beta_1\,z_t+\beta_2\,D_{1t}+\beta_3\,(z_t\cdot D_{1t})+u_t$$
```{r}
#| label: m4
show_coef(m_inter, "Model 4: full interaction", 3)
b <- coef(m_inter); V <- vcov(m_inter); tq <- qt(0.975, df.residual(m_inter))
lincomb <- function(w) {
w <- replace(setNames(numeric(length(b)), names(b)), names(w), w)
est <- sum(w * b); se <- sqrt(drop(t(w) %*% V %*% w))
c(est = est, se = se, lo = est - tq * se, hi = est + tq * se)
}
rl <- rbind(lincomb(c("(Intercept)" = 1)),
lincomb(c("(Intercept)" = 1, "HighFDI" = 1)),
lincomb(c("centr_logGDP" = k10)),
lincomb(c("centr_logGDP" = k10, "centr_logGDP:HighFDI" = k10)),
lincomb(c("HighFDI" = 1)),
lincomb(c("centr_logGDP:HighFDI" = k10)))
reg_tab <- data.frame(
Quantity = c("Level at typical GDP, Low-FDI years", "Level at typical GDP, High-FDI years",
"Slope (pp per +10% GDP), Low-FDI years", "Slope (pp per +10% GDP), High-FDI years",
"Level gap at typical GDP (High − Low)", "Slope difference (High − Low), pp per +10% GDP"),
Estimate = rl[, "est"], `Std. error` = rl[, "se"], `95% CI low` = rl[, "lo"], `95% CI high` = rl[, "hi"],
check.names = FALSE)
brand_table(reg_tab, "What Model 4 implies for each regime, with exact standard errors", 2)
# self-check: Model 4 is exactly two separate regressions
sep_high <- coef(lm(REN_ERG_CONS ~ centr_logGDP, data = subset(df_clean, HighFDI == 1)))
stopifnot(isTRUE(all.equal(unname(sep_high), unname(c(sum(b[c("(Intercept)", "HighFDI")]),
sum(b[c("centr_logGDP", "centr_logGDP:HighFDI")]))))))
show_ftest(m_int, m_inter, "Is the tilt difference needed? Incremental F-test (Model 2 vs Model 4)")
show_ftest(m_base, m_inter, "Are the two regime lines identical? Joint (Chow-style) F-test (Model 1 vs Model 4)")
b3_10 <- unname(coef(m_inter)["centr_logGDP:HighFDI"]) * k10
```
::: {.callout-note}
## What the numbers say
- **Low-FDI years:** at typical GDP the renewable share is about `r f1(rl[1, 1])`%, and every +10% GDP goes with `r sgn(rl[3, 1])` pp.
- **High-FDI years:** the level is about `r f1(rl[2, 1])`%, and the slope is `r sgn(rl[4, 1])` pp per +10% GDP.
- **Tilt difference:** `r sgn(b3_10)` pp per +10% GDP, **`r sig5(f_slope_inc$p)`** (`r ptxt(f_slope_inc$p)`). The two regimes `r if (f_slope_inc$p < 0.05) "respond differently to GDP growth" else "respond to GDP growth in about the same way"`.
- **Are the lines identical overall?** The joint test gives `r ptxt(f_chow$p)`: `r evid(f_chow$p)` that the regimes follow different lines.
:::
::: {.callout-tip}
## In Simple Terms
Model 4 is the "separate rules for each group" model. Its joint test (`r ptxt(f_chow$p)`) is `r if (f_chow$p > f_int$p) "**less** convincing than the simple level shift of Model 2" else "**more** convincing than the simple level shift of Model 2"` (`r ptxt(f_int$p)`). The reason: the joint test spends **two** extra parameters, and when the second one (the tilt) adds little, it dilutes the evidence for the first. Extra flexibility has to pay for itself.
:::
```{r}
#| label: fig-m4
#| fig-cap: "Parallel lines (Model 2, left) versus separate lines (Model 4, right), with 95% confidence bands."
#| fig-width: 11
#| fig-height: 5
pred_inter <- pred_for(m_inter)
(regime_plot(pred_int, "A. Parallel lines (Model 2)", "One tilt, shifted level") |
regime_plot(pred_inter, "B. Separate lines (Model 4)",
paste0("Tilts differ by ", sgn(b3_10), " pp per +10% GDP"), show_y = FALSE)) +
plot_layout(guides = "collect") & theme(legend.position = "bottom")
```
```{r}
#| label: gap-curve
#| fig-cap: "Model 4: the High-FDI minus Low-FDI gap at each GDP level, with 95% band. The grey zone is where both regimes have observed years."
#| fig-width: 8.5
#| fig-height: 4.6
z_lo <- max(min(df_clean$centr_logGDP[df_clean$HighFDI == 1]), min(df_clean$centr_logGDP[df_clean$HighFDI == 0]))
z_hi <- min(max(df_clean$centr_logGDP[df_clean$HighFDI == 1]), max(df_clean$centr_logGDP[df_clean$HighFDI == 0]))
zz <- seq(min(df_clean$centr_logGDP), max(df_clean$centr_logGDP), length.out = 200)
gap_est <- b["HighFDI"] + b["centr_logGDP:HighFDI"] * zz
gap_se <- sqrt(V["HighFDI", "HighFDI"] + zz^2 * V["centr_logGDP:HighFDI", "centr_logGDP:HighFDI"] +
2 * zz * V["HighFDI", "centr_logGDP:HighFDI"])
gap_est <- unname(gap_est)
gc <- data.frame(GDP_bn = exp(zz + mean_lgdp), z = zz, gap = gap_est, lo = gap_est - tq * gap_se, hi = gap_est + tq * gap_se)
gc$sig <- gc$lo > 0 | gc$hi < 0
gc$common <- gc$z >= z_lo & gc$z <= z_hi
ggplot(gc, aes(GDP_bn, gap)) +
annotate("rect", xmin = exp(z_lo + mean_lgdp), xmax = exp(z_hi + mean_lgdp), ymin = -Inf, ymax = Inf,
fill = "grey85", alpha = 0.6) +
geom_hline(yintercept = 0, linetype = "dashed", colour = "grey40") +
geom_ribbon(aes(ymin = lo, ymax = hi), fill = brand, alpha = 0.15) +
geom_line(colour = brand, linewidth = 1.2) +
geom_rug(data = df_clean, aes(x = GDP_bn, colour = FDI_Group), inherit.aes = FALSE, sides = "b", linewidth = 0.8) +
scale_colour_manual(values = pal_fdi, name = "Observed years") +
scale_x_log10(breaks = c(25, 30, 40, 50, 60)) +
labs(title = "Where do the two regimes differ?", x = "GDP (billion USD, log scale)",
y = "High-FDI minus Low-FDI renewable share (pp)") +
theme_brand()
sig_c <- gc[gc$sig & gc$common, ]
sig_txt <- if (nrow(sig_c)) sprintf("from about USD %.0f bn to USD %.0f bn", min(sig_c$GDP_bn), max(sig_c$GDP_bn)) else "nowhere"
gap_at <- function(zv) unname(b["HighFDI"] + b["centr_logGDP:HighFDI"] * zv)
```
::: {.callout-note}
## What the picture says
At the low end of the shared GDP range (about USD `r f1(exp(z_lo + mean_lgdp))` bn) the estimated gap is `r sgn(gap_at(z_lo), 1)` pp; at typical GDP it is `r sgn(gap_at(0), 1)` pp; at the high end (about USD `r f1(exp(z_hi + mean_lgdp))` bn) it is `r sgn(gap_at(z_hi), 1)` pp. Within the zone where both regimes actually have years, the band excludes zero **`r sig_txt`**. Outside the grey zone the lines are extrapolations: one regime has no years there, so those gaps should not be trusted.
:::
## Model 5: two dummies, FDI and trade
*Question: once the FDI regime is accounted for, does trade openness add anything?*
$$REN_t=\beta_0+\beta_1\,z_t+\beta_2\,D_{1t}+\beta_3\,D_{2t}+u_t \qquad H_0:\ \beta_3=0$$
```{r}
#| label: m5
cell <- df_clean |>
group_by(FDI_Group, Trade_Group) |>
summarise(n = n(), mean_ren = mean(REN_ERG_CONS), .groups = "drop") |>
mutate(label = paste0("n = ", n, "\nmean ", f1(mean_ren), "%"))
n_cells <- nrow(cell); r_dd <- cor(df_clean$HighFDI, df_clean$HighTrade)
vif5 <- car::vif(m_dual)
rank5 <- qr(model.matrix(m_dual))$rank
show_coef(m_dual, "Model 5: FDI and trade dummies together", 3)
show_ftest(m_int, m_dual, "Does trade openness add information beyond FDI? Partial F-test (Model 2 vs Model 5)")
```
```{r}
#| label: fig-m5-cells
#| fig-cap: "How Sudan's years fall into the four FDI × trade combinations (count and average renewable share)."
#| fig-width: 7.5
#| fig-height: 4.2
ggplot(cell, aes(FDI_Group, Trade_Group, fill = mean_ren)) +
geom_tile(colour = "white", linewidth = 2) +
geom_text(aes(label = label), fontface = "bold", size = 4.2, colour = "#292929") +
scale_fill_gradient(low = "#EAF1F8", high = "#F2B8BC", name = "Mean renewable\nshare (%)") +
labs(x = "FDI regime (D1)", y = "Trade regime (D2)") +
theme_brand() + theme(panel.grid = element_blank(), legend.position = "right")
```
```{r}
#| label: m5-numbers
#| include: false
b5 <- coef(m_dual); p5 <- summary(m_dual)$coefficients[, 4]
rss_cut <- 100 * f_d2$saved / f_d2$rss_r
```
::: {.callout-note}
## What the numbers say
- **High-trade years (β₃):** at the same GDP and FDI regime, they have a renewable share **`r f2(abs(b5["HighTrade"]))` pp `r dirw(b5["HighTrade"])`** (`r ptxt(p5["HighTrade"])`, `r evid(p5["HighTrade"])`). Adding this single switch removes **`r f1(rss_cut)`%** of the variation that Model 2 left unexplained (F = `r f2(f_d2$F)`).
- **The FDI gap shrinks:** from `r sgn(gap_ctrl)` pp in Model 2 to **`r sgn(b5["HighFDI"])` pp** here (`r ptxt(p5["HighFDI"])`, `r evid(p5["HighFDI"])`). Part of what looked like an "FDI regime effect" was shared with the trade regime.
- **No dummy-variable trap:** all `r n_cells` of the 4 FDI × trade cells contain years, the design matrix has full rank (`r rank5` of `r ncol(model.matrix(m_dual))` columns), and the two dummies are only mildly related (correlation `r f2(r_dd)`; largest VIF `r f2(max(vif5))`), so they do not compete for the same information.
:::
::: {.callout-warning}
## Careful: a dummy can be driven by a few years
In this sample, trade openness falls sharply in the final years (Trade_GDP = `r f1(df_clean$Trade_GDP[df_clean$Year == year_hi - 1])`% in `r year_hi - 1` and `r f1(df_clean$Trade_GDP[df_clean$Year == year_hi])`% in `r year_hi`, against a median of `r f1(med_trade)`%). @sec-influence checks whether a handful of years, not a lasting pattern, produce the trade result.
:::
## Model 6: three industry tiers
*Question: does industry's share of GDP (Low / Medium / High) shift the line?*
$$REN_t=\beta_0+\beta_1\,z_t+\gamma_1\,D_{Medium,t}+\gamma_2\,D_{High,t}+u_t$$
```{r}
#| label: m6
show_coef(m_poly, "Model 6: industry tiers (reference = Low)", 3)
show_ftest(m_base, m_poly, "Do the industry tiers matter jointly? F-test (Model 1 vs Model 6)")
b6 <- coef(m_poly); p6 <- summary(m_poly)$coefficients[, 4]
```
::: {.callout-note}
## What the numbers say
Medium-industry years sit **`r f2(abs(b6["IndTierMedium"]))` pp `r dirw(b6["IndTierMedium"])`** than Low-industry years of the same GDP (`r ptxt(p6["IndTierMedium"])`), and High-industry years **`r f2(abs(b6["IndTierHigh"]))` pp `r dirw(b6["IndTierHigh"])`** (`r ptxt(p6["IndTierHigh"])`). Each coefficient is a comparison with the *Low* group only; to judge the factor as a whole, use the joint F-test: **`r ptxt(f_tier$p)`**, so there is **`r evid(f_tier$p)`** that industrial structure matters beyond GDP.
:::
```{r}
#| label: trap
df_trap <- df_clean |> mutate(D_Low = as.integer(IndTier == "Low"), D_Medium = as.integer(IndTier == "Medium"),
D_High = as.integer(IndTier == "High"))
m_trap <- lm(REN_ERG_CONS ~ centr_logGDP + D_Low + D_Medium + D_High, data = df_trap)
Xtrap <- model.matrix(m_trap)
data.frame(Term = names(coef(m_trap)), Estimate = unname(coef(m_trap)),
Status = ifelse(is.na(coef(m_trap)), "ALIASED: R cannot estimate it", "estimated")) |>
brand_table("The dummy-variable trap: three tier dummies plus an intercept", 3,
bold_rows = which(is.na(coef(m_trap))))
```
::: {.callout-tip}
## In Simple Terms: why R drops one dummy
With an intercept in the model, the three tier switches always add up to 1 (every year is in exactly one tier), which is the intercept column. R is then asked to answer one question twice. The design matrix has **`r ncol(Xtrap)` columns but only `r qr(Xtrap)$rank` independent ones**, so R marks one coefficient `NA`. The rule: **with m categories and an intercept, use m − 1 dummies**; the omitted one becomes the reference group.
:::
# Scoreboard: which model fits best?
```{r}
#| label: scoreboard
ev_word <- function(d) ifelse(d < 0.001, "– (best)", ifelse(d < 2, "barely distinguishable",
ifelse(d < 6, "positive evidence against", ifelse(d < 10, "strong evidence against",
"very strong evidence against"))))
sb <- data.frame(Model = glance_all$Model, `Parameters` = glance_all$k, `R²` = glance_all$R2,
`Adj. R²` = glance_all$adjR2, `Typical miss (pp)` = glance_all$sigma,
AIC = glance_all$AIC, BIC = glance_all$BIC, `ΔBIC vs best` = glance_all$dBIC,
`Evidence against this model (BIC)` = ev_word(glance_all$dBIC), check.names = FALSE)
brand_table(sb, "Fit statistics on the common sample (bold row = lowest BIC)", 3, bold_rows = best_i)
```
```{r}
#| label: fig-scoreboard
#| fig-cap: "Distance of every model from the best BIC. Dashed lines mark the usual 'positive', 'strong' and 'very strong' evidence thresholds (2, 6, 10)."
#| fig-width: 8.5
#| fig-height: 3.8
ggplot(glance_all, aes(dBIC, reorder(Model, -dBIC), colour = dBIC < 0.001)) +
geom_vline(xintercept = c(2, 6, 10), linetype = "dashed", colour = "grey60") +
geom_segment(aes(x = 0, xend = dBIC, yend = reorder(Model, -dBIC)), linewidth = 1.6) +
geom_point(size = 4.5) +
scale_colour_manual(values = c("TRUE" = brand, "FALSE" = brand_blue), guide = "none") +
labs(x = "ΔBIC (higher = worse than the best model)", y = NULL) +
theme_brand()
sec_i <- order(glance_all$BIC)[2]
```
::: {.callout-note}
## What the numbers say
**`r best_short`** has the lowest BIC and `r if (best_aic_i == best_i) "also the lowest AIC" else paste0("(AIC prefers ", short_nm[best_aic_i], ")")`. It misses a typical year by about **`r f1(glance_all$sigma[best_i])` pp**, and explains `r f1(100 * glance_all$adjR2[best_i])`% of the variation (adjusted). The runner-up, `r short_nm[sec_i]`, is `r f1(glance_all$dBIC[sec_i])` BIC units behind: **`r ev_word(glance_all$dBIC[sec_i])`**. The weakest model on this scale is `r short_nm[which.max(glance_all$dBIC)]` (`r f1(max(glance_all$dBIC))` units behind). Remember that $R^2$ can only go up when terms are added, so only adjusted $R^2$, AIC and BIC are fair for choosing.
:::
# Stress tests: can we trust these p-values? {#sec-stress}
## Errors that remember last year
```{r}
#| label: dw-table
dwt <- data.frame(Model = dw_tab$Model, `Durbin–Watson` = dw_tab$DW, `p (Durbin–Watson)` = fmt_p(dw_tab$p_DW),
`p (Breusch–Godfrey, 2 lags)` = fmt_p(dw_tab$p_BG),
Reading = ifelse(dw_tab$p_DW < 0.05 & dw_tab$p_BG < 0.05, "Errors clearly persist",
ifelse(dw_tab$p_DW < 0.05 | dw_tab$p_BG < 0.05, "Some persistence", "No clear persistence")),
check.names = FALSE)
brand_table(dwt, "Residual autocorrelation tests (a Durbin–Watson value near 2 means no first-order autocorrelation)", 3, bold_rows = best_i)
n_dw_bad <- sum(dw_tab$p_DW < 0.05)
```
::: {.callout-note}
## What the numbers say
The Durbin–Watson value is far below 2 for most models (Model 1: **`r f2(dw_tab$DW[1])`**; best model `r best_short`: **`r f2(dw_best)`**), and `r n_dw_bad` of 6 models fail the test at 5%. In plain terms: **a year's unexplained gap tends to be followed by a gap of the same sign the next year**. Ordinary standard errors assume otherwise, so they are too small, and p-values are too optimistic. The best model improves the problem (`r best_short` has the highest DW) but `r if (dw_tab$p_DW[best_i] < 0.05) "does not remove it" else "removes most of it"`.
:::
## Do the conclusions survive honest standard errors? (HAC)
```{r}
#| label: hac-table
hac_show <- data.frame(
Question = hac_tab$Question, `Estimate (pp)` = hac_tab$Estimate,
`p (classical)` = fmt_p(hac_tab$p_classic), `p (HAC)` = fmt_p(hac_tab$p_hac),
`Same verdict at 5%?` = ifelse((hac_tab$p_classic < 0.05) == (hac_tab$p_hac < 0.05), "Yes", "No: flips"),
Strength = hac_tab$Strength, check.names = FALSE)
brand_table(hac_show, "Classical vs Newey–West (HAC) p-values for every headline question", 3)
n_flip <- sum((hac_tab$p_classic < 0.05) != (hac_tab$p_hac < 0.05))
```
::: {.callout-note}
## What the numbers say
Re-testing with HAC standard errors flips the 5% verdict for **`r n_flip` of 6** questions. For the headline FDI question (M2), the p-value moves from **`r fmt_p(hac_tab$p_classic[i_fdi])` to `r fmt_p(hac_tab$p_hac[i_fdi])`**, so it is rated **"`r hac_tab$Strength[i_fdi]`"**. The High-trade gap in Model 5 stays far below 5% under both methods (`r fmt_p(hac_tab$p_classic[i_trade5])` and `r fmt_p(hac_tab$p_hac[i_trade5])`): rated **"`r hac_tab$Strength[i_trade5]`"**. HAC corrections can move p-values either way, so read this table as "which findings are stable?", not as a new set of tests to pick from.
:::
::: {.callout-warning}
## Careful
HAC standard errors rely on large samples, and `r N_obs` annual observations is small. Treat this as a sensitivity check. And note that HAC fixes only the *uncertainty*, not the fact that the regressors may be tracking time (see the timeline in @sec-regimes).
:::
## Does the answer depend on where the line is drawn? {#sec-cutoffs}
```{r}
#| label: fig-sens
#| fig-cap: "Cut-off sensitivity: the FDI regime is redefined at 17 different percentiles. Top: the level gap and its 95% interval. Bottom: p-values (dashed = 0.05). The dotted vertical line is the median used in the main text."
#| fig-width: 9
#| fig-height: 6.2
pA <- ggplot(sens, aes(q, gap)) +
geom_hline(yintercept = 0, colour = "grey40", linetype = "dashed") +
geom_vline(xintercept = 0.5, colour = brand_dark, linetype = "dotted") +
geom_ribbon(aes(ymin = lo, ymax = hi), fill = brand, alpha = 0.15) +
geom_line(colour = brand, linewidth = 1.1) + geom_point(colour = brand, size = 2) +
scale_x_continuous(labels = scales::percent_format(accuracy = 1)) +
labs(title = "Estimated High-FDI gap at the same GDP", x = NULL, y = "pp of renewable share") + theme_brand()
pB <- sens |> select(q, `Gap test (Model 2)` = p_gap, `Joint test (Model 4 vs 1)` = p_joint) |>
pivot_longer(-q, names_to = "Test", values_to = "p") |>
ggplot(aes(q, p, colour = Test)) +
geom_hline(yintercept = 0.05, colour = "grey40", linetype = "dashed") +
geom_vline(xintercept = 0.5, colour = brand_dark, linetype = "dotted") +
geom_line(linewidth = 1.1) + geom_point(size = 2) +
scale_colour_manual(values = c(brand, brand_blue), name = NULL) +
scale_x_continuous(labels = scales::percent_format(accuracy = 1)) +
labs(title = "p-values", x = "Cut-off: a year is 'High-FDI' when FDI is above this percentile", y = "p-value") + theme_brand()
pA / pB
med_row <- sens[abs(sens$q - 0.5) < 1e-9, ]
n_pos <- sum(sens$gap > 0); n_neg <- sum(sens$gap < 0)
n_joint_sig <- sum(sens$p_joint < 0.05)
rank_med <- sum(sens$p_gap < med_row$p_gap) + 1
```
::: {.callout-note}
## What the numbers say
Across `r n_sens` cut-offs from the 30th to the 70th percentile, the estimated gap is **positive in `r n_pos` and negative in `r n_neg`** cut-offs and ranges from `r f2(min(sens$gap))` to `r f2(max(sens$gap))` pp. It is statistically significant at 5% in **`r n_sens_sig` of `r n_sens`** cut-offs, and the joint test in `r n_joint_sig`. The median used in the main text (`r ptxt(med_row$p_gap)`) is **`r if (rank_med > n_sens / 2) "among the less favourable cut-offs" else "among the more favourable cut-offs"`** (rank `r rank_med` of `r n_sens` from most to least significant). So the **direction and rough size of the gap are stable**; its **significance is not guaranteed**: it depends on the chosen line and on how the errors are treated (previous section). A fair write-up reports a range, not a single p-value.
:::
## Could a few years be driving the result? {#sec-influence}
```{r}
#| label: influence
cd <- cooks.distance(best_m)
top <- order(-cd)[1:3]
infl <- data.frame(Year = df_clean$Year[top], `Cook's distance` = unname(cd[top]),
`Rule of thumb (4/N)` = 4 / N_obs, `FDI regime` = as.character(df_clean$FDI_Group[top]),
`Trade regime` = as.character(df_clean$Trade_Group[top]),
`Renewable share (%)` = df_clean$REN_ERG_CONS[top], check.names = FALSE)
brand_table(infl, paste0("The three most influential years in ", best_short, " (Cook's distance)"), 3)
drop_idx <- which.max(cd)
m_leave <- update(best_m, data = df_clean[-drop_idx, ])
cmp <- data.frame(Term = term_label(names(coef(best_m))), `All years` = unname(coef(best_m)),
`Without most influential year` = unname(coef(m_leave)),
`p (all years)` = fmt_p(summary(best_m)$coefficients[, 4]),
`p (without)` = fmt_p(summary(m_leave)$coefficients[, 4]), check.names = FALSE)
brand_table(cmp, paste0(best_short, " with and without ", df_clean$Year[drop_idx]), 3)
# the same question for the last two years (the trade collapse)
last2 <- df_clean$Year %in% c(year_hi - 1, year_hi)
m_last2 <- update(m_dual, data = df_clean[!last2, ])
b_tr_all <- unname(coef(m_dual)["HighTrade"]); b_tr_drop <- unname(coef(m_last2)["HighTrade"])
p_tr_drop <- summary(m_last2)$coefficients["HighTrade", 4]
```
::: {.callout-note}
## What the numbers say
The most influential year in `r best_short` is **`r df_clean$Year[drop_idx]`** (Cook's distance `r f2(cd[drop_idx])`, above the usual 4/N = `r f2(4 / N_obs)` warning level). Dropping it `r if (all(sign(coef(m_leave)) == sign(coef(best_m)))) "leaves every coefficient with the same sign" else "flips the sign of at least one coefficient"`. Separately, dropping the two years when trade collapsed (`r year_hi - 1` and `r year_hi`) changes the High-trade gap from **`r sgn(b_tr_all)` to `r sgn(b_tr_drop)` pp** (`r ptxt(p_tr_drop)`), so the trade result `r if (p_tr_drop < 0.05) "does **not** hinge on those two years" else "**does** depend on those two years"`.
:::
## Residuals of the best model
```{r}
#| label: fig-resid
#| fig-cap: "Residual checks for the best model: residuals vs fitted values (left), normal Q–Q (middle), residuals over time (right)."
#| fig-width: 12
#| fig-height: 4.3
aug <- broom::augment(best_m)
aug$Year <- df_clean$Year
d1 <- ggplot(aug, aes(.fitted, .resid)) +
geom_hline(yintercept = 0, linetype = "dashed", colour = brand) +
geom_point(colour = brand_blue, size = 2.4, alpha = 0.85) +
geom_smooth(method = "loess", formula = y ~ x, se = FALSE, colour = "#292929", linewidth = 0.8) +
labs(title = "Residuals vs fitted", x = "Fitted values (pp)", y = "Residual (pp)") + theme_brand()
d2 <- ggplot(aug, aes(sample = .std.resid)) +
stat_qq(colour = brand_blue, size = 2.4) + stat_qq_line(colour = brand, linewidth = 0.9) +
labs(title = "Normal Q–Q", x = "Theoretical quantiles", y = "Standardised residuals") + theme_brand()
d3 <- ggplot(aug, aes(Year, .resid)) +
geom_hline(yintercept = 0, linetype = "dashed", colour = brand) +
geom_line(colour = "grey70") + geom_point(colour = brand_blue, size = 2.4) +
labs(title = "Residuals over time", x = "Year", y = "Residual (pp)") + theme_brand()
d1 | d2 | d3
runs_changes <- sum(diff(sign(aug$.resid)) != 0)
jb_p <- tryCatch(shapiro.test(aug$.resid)$p.value, error = function(e) NA_real_)
```
::: {.callout-note}
## What the pictures say
- **Left:** a flat smoother around zero means no missed curvature. With only `r N_obs` points, treat small wiggles as noise and only a clear arch or bowl as a warning.
- **Middle:** points close to the line mean roughly normal residuals (Shapiro–Wilk `r ptxt(jb_p)`: `r if (!is.na(jb_p) && jb_p < 0.05) "normality is rejected" else "normality is not rejected"`).
- **Right:** residuals change sign only `r runs_changes` times in `r N_obs - 1` year-to-year steps. Long same-sign stretches are the picture version of the autocorrelation found above.
:::
# Final verdict
```{r}
#| label: verdict-table
claims <- data.frame(
Claim = c("High-FDI years sit at a different level than Low-FDI years of the same GDP",
"The GDP effect (slope) differs between FDI regimes",
"High-trade years sit at a different level, once FDI regime is controlled",
"Industrial structure (three tiers) shifts the line beyond GDP"),
`Estimate` = c(paste0(sgn(hac_tab$Estimate[i_fdi]), " pp"),
paste0(sgn(hac_tab$Estimate[i_slope]), " pp per +10% GDP"),
paste0(sgn(hac_tab$Estimate[i_trade5]), " pp"), "–"),
`p (classical)` = fmt_p(hac_tab$p_classic[c(i_fdi, i_slope, i_trade5, i_tier)]),
`p (HAC)` = fmt_p(hac_tab$p_hac[c(i_fdi, i_slope, i_trade5, i_tier)]),
Strength = hac_tab$Strength[c(i_fdi, i_slope, i_trade5, i_tier)], check.names = FALSE)
brand_table(claims, "Evidence ledger: every claim, its size and how well it survives", 3)
v2_text <- if (f_slope_inc$p >= 0.05) {
paste0("No clear evidence (the extra-tilt test gives ", ptxt(f_slope_inc$p), ")")
} else paste0("Some evidence (the extra-tilt test gives ", ptxt(f_slope_inc$p), ")")
trade_phrase <- switch(hac_tab$Strength[i_trade5],
"Robust" = "it holds under both ordinary and autocorrelation-robust standard errors",
"Fragile" = "it holds under only one of the two kinds of standard errors",
"Weak" = "it is only weakly supported", "there is no clear evidence for it")
```
::: {.callout-important}
## Verdict
1. **Does the FDI regime shift Sudan's renewable share?** At equal GDP, High-FDI years sit about `r f1(abs(gap_ctrl))` pp `r dirw(gap_ctrl)` (a range of `r f1(min(sens$gap))` to `r f1(max(sens$gap))` pp across cut-offs). The direction is stable, but the evidence is **"`r tolower(hac_tab$Strength[i_fdi])`"**: it needs ordinary standard errors and a favourable cut-off to reach 5% significance.
2. **Does FDI change how GDP matters?** `r v2_text`, and Model 3, the only model built to test it without the level shift, is not even stable to the choice of origin.
3. **Does trade openness matter?** The **trade-openness regime** puts years `r f2(abs(b_trade5))` pp `r dirw(b_trade5)` at equal GDP and FDI regime; `r trade_phrase`, and the model containing it is the best-fitting one (`r best_short`).
4. **Industrial structure:** `r tolower(hac_tab$Strength[i_tier])` that the three tiers shift the line beyond GDP.
Everything above is an association in `r N_obs` annual, autocorrelated observations. It does not show that FDI or trade *causes* the renewable share to move.
:::
# Check your understanding
::: {.callout-note collapse="true"}
## 1. What does the High-FDI coefficient of Model 2 mean?
At the **same GDP**, years with above-median FDI had a renewable share **`r f2(abs(gap_ctrl))` pp `r dirw(gap_ctrl)`** than other years. It is a *comparison between groups of years* at a fixed GDP, not what happens to Sudan if FDI rises by one unit.
:::
::: {.callout-note collapse="true"}
## 2. Why do we centre log GDP?
Because the uncentred intercept describes a Sudan with GDP = USD 1 bn (it would be **`r f1(int_unc)`%** of renewable energy, and the dummy would claim a gap of **`r f1(gap_unc)` pp**). Centring moves the reference point to Sudan's typical GDP (about USD `r f1(mean_gdp_bn)` bn) without changing the fit.
:::
::: {.callout-note collapse="true"}
## 3. Why is the joint test of Model 4 (`r ptxt(f_chow$p)`) weaker than the dummy test of Model 2 (`r ptxt(f_int$p)`)?
The joint test spends two parameters. The tilt term adds little (`r ptxt(f_slope_inc$p)`), so it dilutes the evidence carried by the level shift. In a small sample, every extra parameter costs power.
:::
::: {.callout-note collapse="true"}
## 4. Why can't R estimate all three industry-tier dummies together with an intercept?
The three dummies sum to 1, which equals the intercept column: perfect collinearity (the dummy-variable trap). With m categories, use m − 1 dummies.
:::
::: {.callout-note collapse="true"}
## 5. The raw gap is `r f2(abs(gap_raw))` pp but Model 2 gives `r f2(abs(gap_ctrl))` pp. Which is right?
Both are right, for different questions. The raw gap compares averages of two groups that also differ in GDP. Model 2 compares years of equal GDP. The difference is exactly `r sgn(pull)` pp, the GDP head-start of High-FDI years multiplied by the GDP slope (see the accounting table in Model 2).
:::
# Reference guide and workspace
| Specification | What the dummy coefficient means |
|:--------------------------|:-----------------------------------------------------------------|
| $y=\beta_0+\beta_1D+u$ | Exact difference of group averages, $\bar y_{D=1}-\bar y_{D=0}$ |
| $y=\beta_0+\beta_1X+\beta_2D+u$ | Vertical gap between parallel lines, the same at every $X$ |
| $y=\beta_0+\beta_1X+\beta_2D+\beta_3(XD)+u$ | The gap is $\beta_2+\beta_3X$ and **changes with X**; $\beta_2$ is the gap at $X=0$ (so centre $X$ first) |
| Factor with $m$ categories + intercept | $m-1$ coefficients, each a shift vs the omitted reference group |
**Always report:** the reference category, how the groups were built (and that the cut-off is a choice), the F-test of the joint restriction, and a robustness check for autocorrelated errors.
```{r}
#| label: save-workspace
udaje10 <- df_clean
save(udaje10, m_base, m_int, m_slope, m_inter, m_dual, m_poly, models,
file = "pamat_cvicenie10.Rdata")
cat("Saved Exercise 9b models and data (N =", nrow(udaje10), ") to pamat_cvicenie10.Rdata.")
```