---
title: "Multicollinearity in the Sudan Renewable-Energy Model"
subtitle: "Econometrics Exercise 8 | Diagnosis and remedies"
author: "Ahmed Mustafa"
date: today
lang: en
format:
html:
toc: true
toc-location: left
toc-depth: 3
number-sections: true
theme: cosmo
embed-resources: true
code-fold: true
code-tools: true
fig-align: center
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); }
h1, h2, h3 { color: var(--brand-dark); }
h1 { border-bottom: 2px solid var(--brand); padding-bottom: .25rem; }
.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; }
```
```{r}
#| label: setup
#| include: false
required_packages <- c("dplyr", "tidyr", "ggplot2", "broom", "knitr",
"kableExtra", "car", "lmtest", "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(ggplot2)
library(broom)
library(knitr)
library(kableExtra)
options(knitr.kable.NA = "–")
# ---- Brand identity (identical to Exercises 4, 5 and 7) -------------------
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) {
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)
}
theme_brand <- function(base_size = 12) {
theme_minimal(base_size = base_size) +
theme(plot.title = element_text(colour = brand_dark, face = "bold"),
panel.grid.minor = element_blank(),
legend.position = "bottom")
}
# ---- Small formatting helpers ---------------------------------------------
fmt_p <- function(p) ifelse(is.na(p), "–",
ifelse(p < 0.001, "< 0.001", sprintf("%.3f", p)))
f3 <- function(x, d = 3) formatC(x, format = "f", digits = d)
stars <- function(p) as.character(cut(p, c(-Inf, .001, .01, .05, .1, Inf),
labels = c("***", "**", "*", ".", ""),
right = FALSE))
vif_label <- function(v) as.character(cut(v, c(-Inf, 5, 10, Inf), right = FALSE,
labels = c("Low (< 5)", "Moderate (5–10)", "Severe (≥ 10)")))
# ---- Table builders used throughout ---------------------------------------
coef_table <- function(model) {
broom::tidy(model, conf.int = TRUE) |>
transmute(Variable = term, Estimate = estimate, `Std. error` = std.error,
`t statistic` = statistic, `p-value` = fmt_p(p.value),
`Sig.` = stars(p.value),
`95% CI` = sprintf("[%.3f, %.3f]", conf.low, conf.high))
}
fit_table <- function(models) {
bind_rows(lapply(names(models), function(nm) {
g <- broom::glance(models[[nm]])
data.frame(Model = nm, N = g$nobs, `R²` = g$r.squared,
`Adj. R²` = g$adj.r.squared, Sigma = g$sigma,
`F` = g$statistic, `p (F)` = fmt_p(g$p.value),
AIC = g$AIC, BIC = g$BIC, check.names = FALSE)
}))
}
tabulka_vif <- function(model) { # VIF is computed by car::vif()
v <- car::vif(model)
data.frame(Variable = names(v), VIF = unname(v),
Assessment = vif_label(unname(v)))
}
f_table <- function(m_restricted, m_unrestricted) {
a <- anova(m_restricted, m_unrestricted)
data.frame(Model = c("Restricted", "Unrestricted"),
`Res. df` = a$Res.Df, RSS = a$RSS, `df diff` = a$Df,
`Sum of sq.` = a$`Sum of Sq`, `F` = a$F,
`p-value` = fmt_p(a$`Pr(>F)`), check.names = FALSE)
}
heatmap_cor <- function(R, title) {
d <- as.data.frame(as.table(R))
names(d) <- c("Var1", "Var2", "r")
d$Var1 <- factor(d$Var1, levels = rev(colnames(R)))
d$Var2 <- factor(d$Var2, levels = colnames(R))
ggplot(d, aes(Var2, Var1, fill = r)) +
geom_tile(colour = "white") +
geom_text(aes(label = sprintf("%.2f", r), colour = abs(r) > 0.7),
fontface = "bold", size = 3.6, show.legend = FALSE) +
scale_colour_manual(values = c("TRUE" = "white", "FALSE" = "black")) +
scale_fill_gradient2(low = brand_blue, mid = "white", high = brand,
limits = c(-1, 1), name = "Correlation") +
labs(title = title, x = NULL, y = NULL) +
theme_brand() +
theme(axis.text.x = element_text(angle = 35, hjust = 1))
}
```
# Roadmap
::: {.callout-note}
## Workflow
Multicollinearity means that some regressors are (almost) linear combinations of the others. The OLS estimates stay **unbiased**, but individual coefficients become **imprecise**: large standard errors, small t-statistics, unstable signs.
In order to finish this exercise, five steps are applied to **Sudan's annual data (FDI and renewable energy)**:
1. **Diagnose** the baseline model: correlations, VIF, condition number.
2. **Create** a stronger problem on purpose with a quadratic term in log GDP.
3. **Remedy I:** drop the redundant term (if justified).
4. **Remedy II:** transform or center the regressors.
5. **Remedy III:** basic ridge regression.
:::
::: {.callout-warning}
## Two limitations specific to this dataset
- **Annual time series, not a cross-section.** Sudan's series is short and trending, so regressors that move together over time are a natural source of collinearity. Autocorrelation in the errors is a *separate* problem that also distorts standard errors.
- **Course convention:** the matrix of regressors $\mathbf X$ is treated as fixed (deterministic). VIF, eigenvalues and the condition number fit this convention. The Farrar–Glauber test assumes random regressors, so it is shown only as a supplement.
:::
# Data and workspace
## Restore the cleaned Sudan data
The cleaned `sudan_clean` object is restored from a saved workspace instead of re-importing and re-cleaning the CSV.
```{r}
#| label: load-data
analysis_vars <- c("REN_ERG_CONS", "FDI_GDP", "GDP_billions",
"IND_VA_GDP", "NODA_RCV", "Trade_GDP")
regressors <- setdiff(analysis_vars, "REN_ERG_CONS")
load_sudan <- function() {
candidates <- c("sudan_exercise7_forecasting_results.RData",
"sudan_exercise5_results.RData",
"sudan_exercise5_workspace.RData")
for (f in candidates[file.exists(candidates)]) {
e <- new.env(parent = baseenv())
load(f, envir = e)
if (exists("sudan_clean", envir = e, inherits = FALSE)) {
return(list(data = get("sudan_clean", envir = e), source = f))
}
}
csv <- c("udaje/LDC-Panel-Data.csv", "LDC-Panel-Data.csv")
csv <- csv[file.exists(csv)]
if (!length(csv)) {
stop("No saved workspace and no LDC-Panel-Data.csv found. ",
"Place one of them in the working directory or in 'udaje/'.")
}
raw <- read.csv(csv[1], na.strings = c("", "NA"), stringsAsFactors = FALSE)
d <- raw |>
filter(Country_Code == "SDN") |>
mutate(GDP_billions = GDP_USD / 1e9) |>
arrange(Year) |>
filter(if_all(all_of(analysis_vars), ~ !is.na(.x)))
list(data = d, source = csv[1])
}
loaded <- load_sudan()
udaje8 <- loaded$data |>
mutate(Year = as.integer(as.character(Year))) |>
arrange(Year) |>
select(Year, all_of(analysis_vars)) |>
as.data.frame()
stopifnot(
all(is.finite(as.matrix(udaje8))),
all(udaje8$GDP_billions > 0), # needed for log(GDP)
!anyDuplicated(udaje8$Year),
nrow(udaje8) > length(regressors) + 5
)
n8 <- nrow(udaje8)
data.frame(
Item = c("Country", "Data source", "Period", "Observations (n)",
"Regressors in baseline (k)", "Observations per parameter"),
Value = c("Sudan", loaded$source, paste(min(udaje8$Year), max(udaje8$Year), sep = "–"),
n8, length(regressors), f3(n8 / (length(regressors) + 1), 1))
) |> brand_table("Analysis sample")
```
## Do the regressors move together over time?
Because the data are a time series, a common trend is the first thing to check.
```{r}
#| label: trend-plot
#| fig-cap: "Sudan's regressors over time (each panel has its own scale)."
#| fig-width: 9
#| fig-height: 6.5
udaje8 |>
select(Year, all_of(regressors)) |>
tidyr::pivot_longer(-Year, names_to = "Variable", values_to = "Value") |>
ggplot(aes(Year, Value)) +
geom_line(colour = brand_blue, linewidth = 0.8) +
geom_point(colour = brand, size = 1.4) +
facet_wrap(~ Variable, scales = "free_y", ncol = 2) +
labs(title = "Regressors over time", x = "Year", y = NULL) +
theme_brand()
```
```{r}
#| label: trend-cor
trend_cor <- data.frame(
Variable = regressors,
`Correlation with Year` = sapply(regressors, function(v) cor(udaje8[[v]], udaje8$Year)),
check.names = FALSE
) |> arrange(desc(abs(`Correlation with Year`)))
brand_table(trend_cor, "Correlation of each regressor with calendar time", 3)
strongest_trend <- trend_cor$Variable[1]
strongest_trend_r <- trend_cor$`Correlation with Year`[1]
```
::: {.callout-note}
## Interpretation
`r strongest_trend` has the strongest time trend (correlation with `Year` = `r f3(strongest_trend_r, 2)`). Any two regressors that both trend strongly will be correlated with each other **even if they are economically unrelated**. This is "spurious" collinearity from common trends, and it is the main reason to expect an imprecise multiple regression with only `r n8` observations.
:::
# What multicollinearity does and does not do
For the coefficient of regressor $x_j$ (fixed $\mathbf X$, $E(\mathbf u)=0$, $Var(\mathbf u)=\sigma^2\mathbf I$):
$$
Var(\hat\beta_j)=\frac{\sigma^2}{\sum_i (x_{ji}-\bar x_j)^2}\cdot VIF_j,
\qquad VIF_j=\frac{1}{1-R_j^2}.
$$
$R_j^2$ comes from the **auxiliary regression** of $x_j$ on all the other regressors. A $VIF_j$ of 5 means the standard error is $\sqrt5\approx2.2$ times larger than it would be if $x_j$ were uncorrelated with the others.
::: {.callout-tip}
## Can cause
- Large standard errors and wide confidence intervals for individual coefficients
- Small $|t|$ values and "insignificant" variables despite a good overall fit
- Estimates that swing when one observation or one regressor is added or removed
:::
::: {.callout-important}
## Does *not* cause
- **Bias:** $\hat{\boldsymbol\beta}=\boldsymbol\beta+(\mathbf X^\mathsf T\mathbf X)^{-1}\mathbf X^\mathsf T\mathbf u$, so $E(\hat{\boldsymbol\beta})=\boldsymbol\beta$ whenever $E(\mathbf u)=0$.
- Heteroscedasticity or autocorrelation, or a low $R^2$ or poor forecasts.
Bias comes from **specification errors** (omitted variables, endogeneity), not from collinearity. This distinction matters when choosing a remedy.
:::
# Baseline model
The baseline is the following multiple regression formula:
$$
REN_t=\beta_0+\beta_1FDI_t+\beta_2GDP_t+\beta_3Industry_t+\beta_4ODA_t+\beta_5Trade_t+u_t .
$$
```{r}
#| label: baseline-model
m_base <- lm(REN_ERG_CONS ~ FDI_GDP + GDP_billions + IND_VA_GDP +
NODA_RCV + Trade_GDP, data = udaje8)
brand_table(coef_table(m_base), "Baseline OLS estimates (full sample)", 4)
brand_table(fit_table(list("Baseline (5 regressors)" = m_base)),
"Baseline fit and overall F-test", 4)
```
```{r}
#| label: baseline-numbers
ct <- broom::tidy(m_base) |> filter(term != "(Intercept)")
n_sig <- sum(ct$p.value < 0.05)
k_reg <- nrow(ct)
gb <- broom::glance(m_base)
dw_p <- lmtest::dwtest(m_base)$p.value
symptom_text <- if (gb$r.squared >= 0.7 && n_sig < k_reg) {
"A high joint fit combined with weaker individual t-tests is the classic symptom of multicollinearity. It is only a hint, so the next section checks it formally."
} else {
"There is no obvious mismatch between the joint and individual tests, but collinearity can still be present, so we check it formally."
}
```
::: {.callout-note}
## Interpretation
The model explains `r f3(100 * gb$r.squared, 1)`% of the variation in renewable energy consumption ($R^2$ = `r f3(gb$r.squared)`, adjusted $R^2$ = `r f3(gb$adj.r.squared)`), and the overall F-test p-value is `r fmt_p(gb$p.value)`. Individually, **`r n_sig` of `r k_reg`** slope coefficients are significant at 5%. `r symptom_text`
Side note: the Durbin–Watson test on these residuals gives p = `r fmt_p(dw_p)`. Autocorrelation is a different problem from collinearity, but it would also make the standard errors above unreliable.
:::
# Diagnosing multicollinearity
## Correlation matrix and heatmap
The heatmap shows the pairwise Pearson correlations (numbers are printed in the cells). Blue is negative, white is near zero, red is positive. It is just a graphical display of the correlation matrix, not a test.
```{r}
#| label: heatmap-base
#| fig-cap: "Correlations among the baseline regressors (no constant column)."
#| fig-width: 7
#| fig-height: 5.5
R8 <- cor(udaje8[, regressors])
heatmap_cor(R8, "Correlations among baseline regressors")
top_pairs <- as.data.frame(as.table(R8)) |>
filter(as.character(Var1) < as.character(Var2)) |>
transmute(`Variable 1` = as.character(Var1), `Variable 2` = as.character(Var2),
Correlation = Freq) |>
arrange(desc(abs(Correlation)))
brand_table(head(top_pairs, 3), "Three most correlated pairs of regressors", 3)
```
::: {.callout-note}
## Interpretation
The most correlated pair is **`r top_pairs[[1, "Variable 1"]]` and `r top_pairs[[1, "Variable 2"]]`** (r = `r f3(top_pairs$Correlation[1], 2)`). Pairwise correlations are only a first look. A regressor can be almost a *combination* of two or three others without any single large pairwise correlation, which is why the VIF is the main tool.
:::
## Variance inflation factors (VIF)
```{r}
#| label: vif-base
vif_base <- tabulka_vif(m_base)
brand_table(vif_base, "VIF in the baseline model", 3)
max_vif_base <- max(vif_base$VIF)
max_vif_base_var <- vif_base$Variable[which.max(vif_base$VIF)]
max_r2_aux <- 1 - 1 / max_vif_base
verdict_base <- if (max_vif_base >= 10) {
"This is severe by the usual rule of thumb. Standard errors for this variable are heavily inflated, but that alone is not a reason to drop it: first ask whether it is economically needed."
} else if (max_vif_base >= 5) {
"This is moderate. Precision is clearly affected, so interpret that coefficient with care and check how stable it is."
} else {
"This is below the usual thresholds. Collinearity is **not** a serious problem in the baseline model, so there is no case for dropping or transforming anything for this reason."
}
```
::: {.callout-note}
## Interpretation
The highest VIF belongs to **`r max_vif_base_var`** (VIF = `r f3(max_vif_base, 2)`). The other regressors explain `r f3(100 * max_r2_aux, 1)`% of its variation ($R_j^2$ = `r f3(max_r2_aux, 3)`), and its standard error is about `r f3(sqrt(max_vif_base), 2)` times larger than under orthogonality. `r verdict_base`
The VIF thresholds 5 and 10 are rules of thumb, not critical values of a test.
:::
## Eigenvalues and condition number
If the correlation matrix of the regressors has an eigenvalue close to zero, the regressors are close to a linear dependence. The condition index of component $j$ is $\sqrt{\lambda_{\max}/\lambda_j}$, and $\kappa$ is the largest of them.
```{r}
#| label: eigen-base
ev <- eigen(R8, symmetric = TRUE)$values
kappa_base <- sqrt(max(ev) / min(ev))
data.frame(Component = seq_along(ev), Eigenvalue = ev,
`Condition index` = sqrt(max(ev) / ev), check.names = FALSE) |>
brand_table("Spectral diagnostics of the regressor correlation matrix", 3)
```
::: {.callout-note}
## Interpretation
The smallest eigenvalue is `r f3(min(ev), 3)` and the condition number is $\kappa$ = `r f3(kappa_base, 2)`. A commonly quoted guide is that values above about 30 signal serious near-dependence, but this cut-off is not universal and depends on the standardisation. Read $\kappa$ together with the VIFs: here the two `r if (max_vif_base < 5 && kappa_base < 30) "agree that the baseline is fine" else "point to some collinearity worth following up"`.
:::
## Supplementary: Farrar–Glauber test
```{r}
#| label: farrar-glauber
p8 <- ncol(R8)
fg_chi2 <- -(n8 - 1 - (2 * p8 + 5) / 6) * log(det(R8))
fg_df <- p8 * (p8 - 1) / 2
fg_p <- pchisq(fg_chi2, df = fg_df, lower.tail = FALSE)
data.frame(Test = "Farrar–Glauber (overall)", `Chi-square` = fg_chi2,
df = fg_df, `p-value` = fmt_p(fg_p), check.names = FALSE) |>
brand_table("Farrar–Glauber test (H0: the regressors are mutually uncorrelated)", 3)
```
::: {.callout-warning}
## Use with care
The test assumes *random* regressors, which conflicts with our fixed-$\mathbf X$ convention. It also tends to reject whenever correlations are non-zero, however small. Here p = `r fmt_p(fg_p)`. A rejection means "not all uncorrelated", **not** "dangerous multicollinearity". Base decisions on the VIF and $\kappa$.
:::
# Creating a stronger problem: the quadratic term
If the baseline VIFs are modest, a serious case can be built from *real* data by adding a quadratic term. We replace GDP by $\ln(GDP)$ and add its square:
$$
REN_t=\beta_0+\beta_1FDI_t+\beta_2\ln GDP_t+\beta_3(\ln GDP_t)^2+\beta_4Industry_t+\beta_5ODA_t+\beta_6Trade_t+u_t .
$$
The model is still **linear in the parameters**. The new regressors $\ln GDP$ and $(\ln GDP)^2$ can nevertheless be almost perfectly correlated.
```{r}
#| label: poly-models
udaje8$logGDP <- log(udaje8$GDP_billions)
udaje8$logGDP2 <- udaje8$logGDP^2
m_nogdp <- lm(REN_ERG_CONS ~ FDI_GDP + IND_VA_GDP + NODA_RCV + Trade_GDP, data = udaje8)
m_log <- lm(REN_ERG_CONS ~ FDI_GDP + logGDP + IND_VA_GDP + NODA_RCV + Trade_GDP, data = udaje8)
m_poly <- lm(REN_ERG_CONS ~ FDI_GDP + logGDP + logGDP2 + IND_VA_GDP + NODA_RCV + Trade_GDP, data = udaje8)
poly_regressors <- c("FDI_GDP", "logGDP", "logGDP2", "IND_VA_GDP", "NODA_RCV", "Trade_GDP")
R8_poly <- cor(udaje8[, poly_regressors])
r_log_sq <- cor(udaje8$logGDP, udaje8$logGDP2)
vif_poly <- tabulka_vif(m_poly)
brand_table(vif_poly, "VIF in the quadratic model", 3)
```
```{r}
#| label: heatmap-poly
#| fig-cap: "Correlations after adding the quadratic term."
#| fig-width: 7.5
#| fig-height: 6
heatmap_cor(R8_poly, "Correlations in the quadratic model")
```
```{r}
#| label: poly-numbers
max_vif_poly <- max(vif_poly$VIF)
max_vif_poly_var <- vif_poly$Variable[which.max(vif_poly$VIF)]
```
::: {.callout-note}
## Interpretation
$\ln GDP$ and $(\ln GDP)^2$ have a correlation of **`r f3(r_log_sq, 4)`**. The largest VIF is now `r f3(max_vif_poly, 1)` (`r max_vif_poly_var`), compared with `r f3(max_vif_base, 2)` in the baseline. The collinearity was created by the functional form, because a variable and its own square are nearly the same series whenever the variable stays far from zero.
:::
## Joint fit versus individual t-tests
```{r}
#| label: poly-results
brand_table(coef_table(m_poly), "Quadratic model: coefficient estimates", 4)
brand_table(fit_table(list("No GDP terms" = m_nogdp,
"Log GDP only" = m_log,
"Log GDP + square" = m_poly)),
"Fit of the nested specifications", 4)
```
The overall F-test cannot isolate the two GDP terms (other regressors may be significant). So we test them **jointly**, against the model without any GDP term:
$$H_0:\ \beta_{\ln GDP}=\beta_{(\ln GDP)^2}=0 .$$
```{r}
#| label: joint-gdp-test
brand_table(f_table(m_nogdp, m_poly), "Partial F-test: joint contribution of ln GDP and (ln GDP)²", 4)
a_joint <- anova(m_nogdp, m_poly)
p_joint <- a_joint$`Pr(>F)`[2]
cp <- broom::tidy(m_poly)
p_l1 <- cp$p.value[cp$term == "logGDP"]
p_l2 <- cp$p.value[cp$term == "logGDP2"]
signature_text <- if (p_joint < 0.05 && p_l1 >= 0.05 && p_l2 >= 0.05) {
"This is the textbook multicollinearity signature: the two GDP terms are jointly significant, but neither is individually significant because their standard errors are inflated."
} else if (p_joint < 0.05) {
"The GDP terms are jointly significant and at least one is also individually significant, so the inflated standard errors have not hidden their contribution here."
} else {
"The GDP terms are not jointly significant either, so the weak t-tests are not only a collinearity artefact: once the controls are in, the data give little evidence for any GDP effect."
}
```
::: {.callout-note}
## Interpretation
Individual t-test p-values: $\ln GDP$ = `r fmt_p(p_l1)`, $(\ln GDP)^2$ = `r fmt_p(p_l2)`. Joint F-test p-value: `r fmt_p(p_joint)`. `r signature_text`
The F-test and the t-tests do not contradict each other because they test **different hypotheses**. A t-test asks "is this term needed given all the others?", and with nearly duplicate regressors the answer is hard to give. Therefore a high VIF is **not proof** that the quadratic term is wrong or irrelevant, and decisions should not rest on individual p-values alone.
:::
# Remedy I: drop the redundant term
We compare the model with the square ($M_U$) with the model without it ($M_R$), testing $H_0:\beta_{(\ln GDP)^2}=0$.
```{r}
#| label: remedy-drop
brand_table(f_table(m_log, m_poly), "Partial F-test: is the quadratic term needed?", 4)
brand_table(fit_table(list("Without square (M_R)" = m_log, "With square (M_U)" = m_poly)),
"Fit comparison with and without the quadratic term", 4)
brand_table(tabulka_vif(m_log), "VIF after dropping the quadratic term", 3)
a_quad <- anova(m_log, m_poly)
p_quad <- a_quad$`Pr(>F)`[2]
aic_pair <- AIC(m_log, m_poly)$AIC
bic_pair <- BIC(m_log, m_poly)$BIC
aic_pick <- c("without the square", "with the square")[which.min(aic_pair)]
bic_pick <- c("without the square", "with the square")[which.min(bic_pair)]
vif_after_drop <- max(tabulka_vif(m_log)$VIF)
```
::: {.callout-note}
## Interpretation
- **F-test:** p = `r fmt_p(p_quad)`. `r if (p_quad < 0.05) "The square adds significant explanatory power, so dropping it would remove a real feature of the data." else "There is no significant evidence that the square is needed once log GDP is in the model."`
- **Information criteria:** AIC prefers the model **`r aic_pick`**, and BIC prefers the model **`r bic_pick`**. BIC penalises extra parameters more heavily, so it favours simpler models more often.
- **Collinearity after the drop:** the largest VIF falls to `r f3(vif_after_drop, 2)`.
Decision for the write-up: `r if (p_quad < 0.05) "keep the quadratic specification and handle the collinearity by centring (Remedy II) or ridge (Remedy III)" else "the simpler log specification is statistically defensible and removes the collinearity"`.
:::
::: {.callout-warning}
## Never drop a variable just because its VIF is high
If the variable is relevant, dropping it creates **omitted-variable bias**, which is worse than imprecision. An insignificant coefficient also does not prove the true effect is zero. Combine theory, tests, diagnostics and the purpose of the model.
:::
# Remedy II: transformation and centring
## Log transformation of GDP
```{r}
#| label: remedy-log
brand_table(fit_table(list("Linear GDP" = m_base, "Log GDP" = m_log)),
"Linear versus log GDP (same dependent variable, same sample)", 4)
bind_rows(
tabulka_vif(m_base) |> mutate(Model = "Linear GDP"),
tabulka_vif(m_log) |> mutate(Model = "Log GDP")
) |>
select(Model, Variable, VIF, Assessment) |>
brand_table("VIF: linear versus log GDP", 3)
d_aic <- AIC(m_log) - AIC(m_base)
gdp_vif_lin <- tabulka_vif(m_base)$VIF[tabulka_vif(m_base)$Variable == "GDP_billions"]
gdp_vif_log <- tabulka_vif(m_log)$VIF[tabulka_vif(m_log)$Variable == "logGDP"]
effect_1pct <- 0.01 * coef(m_log)["logGDP"]
```
::: {.callout-note}
## Interpretation
Moving from linear to log GDP changes AIC by `r f3(d_aic, 2)` (`r if (d_aic < 0) "an improvement" else "no improvement"`), and the VIF of the GDP term goes from `r f3(gdp_vif_lin, 2)` to `r f3(gdp_vif_log, 2)`. A log transformation therefore **does not automatically reduce VIF**. Choose it for its economic meaning: here, a 1% rise in GDP is associated with a change of about `r f3(effect_1pct, 3)` percentage points in the renewable share, holding the other regressors constant (natural log).
:::
## Centring the polynomial
Define $z_t=\ln GDP_t-\overline{\ln GDP}$ and use $z_t$ and $z_t^2$ instead of $\ln GDP_t$ and $(\ln GDP_t)^2$. This is only a re-parametrisation of the same regression function, so **fitted values and residuals cannot change**.
```{r}
#| label: remedy-centre
udaje8$z <- udaje8$logGDP - mean(udaje8$logGDP)
udaje8$z2 <- udaje8$z^2
m_poly_c <- lm(REN_ERG_CONS ~ FDI_GDP + z + z2 + IND_VA_GDP + NODA_RCV + Trade_GDP,
data = udaje8)
vif_poly_c <- tabulka_vif(m_poly_c)
bind_rows(vif_poly |> mutate(Model = "Before centring"),
vif_poly_c |> mutate(Model = "After centring")) |>
select(Model, Variable, VIF, Assessment) |>
brand_table("VIF before and after centring", 3)
data.frame(
Check = c("Largest difference in fitted values", "Largest difference in residuals",
"Difference in R²"),
Value = c(max(abs(fitted(m_poly) - fitted(m_poly_c))),
max(abs(residuals(m_poly) - residuals(m_poly_c))),
abs(summary(m_poly)$r.squared - summary(m_poly_c)$r.squared))
) |> brand_table("Equivalence check: centred and uncentred models are the same fit", 12)
r_z <- cor(udaje8$z, udaje8$z2)
max_vif_c <- max(vif_poly_c$VIF)
```
::: {.callout-note}
## Interpretation
Centring cuts the correlation between the two polynomial terms from `r f3(r_log_sq, 4)` to `r f3(r_z, 4)`, and the largest VIF drops from `r f3(max_vif_poly, 1)` to `r f3(max_vif_c, 2)`. The equivalence table shows that fitted values, residuals and $R^2$ are identical up to rounding.
**How can VIF fall if the fit does not change?** VIF measures the precision of **individual coefficients**, and centring changes what those coefficients *mean*. Before centring, $\hat\beta_{\ln GDP}$ is the slope at $\ln GDP=0$ (a GDP of 1 billion USD), at the edge of the data, where it is hard to pin down. After centring, $\hat\alpha_z$ is the slope **at the average log GDP**, which the data identify much better. Centring improves interpretation and precision, but it adds **no new information**.
:::
# Remedy III: ridge regression
Ridge regression shrinks coefficients by penalising their size:
$$
\hat{\boldsymbol\beta}_{Ridge}=(\mathbf X^\mathsf T\mathbf X+\lambda\mathbf I)^{-1}\mathbf X^\mathsf T\mathbf y,\qquad \lambda\ge0 .
$$
We use the quadratic model, **standardised regressors** and a **centred** dependent variable. The intercept is not penalised. For $\lambda=0$ we recover OLS, and for $\lambda>0$ the estimator is **biased** but has a smaller variance.
```{r}
#| label: ridge-setup
Xmat <- as.matrix(udaje8[, poly_regressors])
y8 <- udaje8$REN_ERG_CONS
Xs <- scale(Xmat)
x_mean <- attr(Xs, "scaled:center")
x_sd <- attr(Xs, "scaled:scale")
yc <- y8 - mean(y8)
ridge_beta <- function(lambda) {
b <- as.numeric(solve(crossprod(Xs) + lambda * diag(ncol(Xs)), crossprod(Xs, yc)))
names(b) <- colnames(Xs)
b
}
lambda_grid <- c(0, 1, 5, 10, 30, 100, 300)
ridge_path <- sapply(lambda_grid, ridge_beta) # rows: variables, columns: lambda
colnames(ridge_path) <- lambda_grid
data.frame(lambda = lambda_grid, t(ridge_path), check.names = FALSE) |>
brand_table("Ridge coefficients on the standardised scale", 4)
```
```{r}
#| label: ridge-plot
#| fig-cap: "Ridge coefficient paths (standardised regressors). The horizontal axis is on a pseudo-log scale."
#| fig-width: 8.5
#| fig-height: 5
path_long <- data.frame(lambda = lambda_grid, t(ridge_path), check.names = FALSE) |>
tidyr::pivot_longer(-lambda, names_to = "Variable", values_to = "Coefficient")
ggplot(path_long, aes(lambda, Coefficient, colour = Variable, shape = Variable)) +
geom_hline(yintercept = 0, colour = "grey60", linetype = "dashed") +
geom_line(linewidth = 0.9) +
geom_point(size = 2.4) +
scale_x_continuous(trans = scales::pseudo_log_trans(base = 10), breaks = lambda_grid) +
scale_colour_manual(values = brand_cols) +
labs(title = "Ridge regression: coefficient paths", x = expression(lambda),
y = "Standardised coefficient", colour = NULL, shape = NULL) +
theme_brand()
```
```{r}
#| label: ridge-numbers
b_logGDP_0 <- ridge_path["logGDP", "0"]; b_logGDP_30 <- ridge_path["logGDP", "30"]
b_logGDP2_0 <- ridge_path["logGDP2", "0"]; b_logGDP2_30 <- ridge_path["logGDP2", "30"]
```
::: {.callout-note}
## Interpretation
At $\lambda=0$ (OLS) the two GDP terms have large coefficients of `r f3(b_logGDP_0, 2)` and `r f3(b_logGDP2_0, 2)`. If these have opposite signs, they are cancelling each other, which is a typical collinearity pattern. At $\lambda=30$ they shrink to `r f3(b_logGDP_30, 2)` and `r f3(b_logGDP2_30, 2)`. The more collinear a group of regressors, the faster ridge shrinks their coefficients, while well-identified regressors move much less.
:::
## Choosing $\lambda$ by leave-one-out cross-validation
Ridge is a linear smoother, so the leave-one-out residual has a closed form, $e_i/(1-h_{ii})$, where $h_{ii}$ is the leverage from the ridge hat matrix.
```{r}
#| label: ridge-cv
loo_rmse <- function(lambda) {
A <- solve(crossprod(Xs) + lambda * diag(ncol(Xs)))
H <- Xs %*% A %*% t(Xs)
e <- as.numeric(yc - H %*% yc)
h <- diag(H) + 1 / n8 # + leverage of the (unpenalised) intercept
sqrt(mean((e / (1 - h))^2))
}
lambda_cv <- c(0, 0.5, 1, 2, 5, 10, 20, 30, 50, 100, 200, 300)
cv_table <- data.frame(lambda = lambda_cv, `LOO-CV RMSE` = sapply(lambda_cv, loo_rmse),
check.names = FALSE)
brand_table(cv_table, "Leave-one-out cross-validated RMSE (percentage points)", 4)
pos <- cv_table$lambda > 0
lambda_demo <- cv_table$lambda[pos][which.min(cv_table$`LOO-CV RMSE`[pos])]
rmse_ols <- cv_table$`LOO-CV RMSE`[cv_table$lambda == 0]
rmse_ridge <- min(cv_table$`LOO-CV RMSE`[pos])
```
```{r}
#| label: ridge-original-units
beta_std <- ridge_beta(lambda_demo)
beta_orig <- beta_std / x_sd
beta0 <- mean(y8) - sum(beta_orig * x_mean)
beta_ridge <- c("(Intercept)" = beta0, beta_orig)
data.frame(
Variable = names(coef(m_poly)),
OLS = as.numeric(coef(m_poly)),
Ridge = as.numeric(beta_ridge[names(coef(m_poly))])
) |>
mutate(`Ridge / OLS` = Ridge / OLS) |>
brand_table(paste0("OLS and ridge (lambda = ", lambda_demo,
") in original units"), 4)
fit_ridge <- beta0 + as.numeric(Xmat %*% beta_orig)
r2_ridge <- 1 - sum((y8 - fit_ridge)^2) / sum((y8 - mean(y8))^2)
r2_ols <- summary(m_poly)$r.squared
```
::: {.callout-note}
## Interpretation
Cross-validation picks $\lambda$ = `r lambda_demo` (among positive values on the grid). Its LOO-CV RMSE is `r f3(rmse_ridge, 3)` against `r f3(rmse_ols, 3)` for OLS, `r if (rmse_ridge < rmse_ols) "so shrinkage improves out-of-sample accuracy" else "so shrinkage does not help here"`. In-sample $R^2$ falls only from `r f3(r2_ols, 3)` to `r f3(r2_ridge, 3)`, which is the price of the bias.
:::
::: {.callout-warning}
## Limits of this ridge demonstration
- Ridge coefficients are biased, so **the usual t-tests and standard errors do not apply** to them.
- Leave-one-out CV treats observations as exchangeable. For a trending annual series it is optimistic, and a rolling-origin evaluation would be more honest.
- Ridge is mainly a **prediction** tool. It does not answer whether "FDI has an effect".
- For serious use, take $\lambda$ from a package such as `glmnet`, with standardisation done inside each cross-validation fold.
:::
# Key results and decision guide
```{r}
#| label: key-numbers
data.frame(
Check = c("Baseline: largest VIF", "Baseline: condition number κ",
"Quadratic model: largest VIF", "After centring: largest VIF",
"Joint test of the GDP terms (p-value)", "Is the square needed? (p-value)",
"Best ridge λ and LOO-CV RMSE vs OLS"),
Result = c(paste0(f3(max_vif_base, 2), " (", max_vif_base_var, ")"),
f3(kappa_base, 2),
paste0(f3(max_vif_poly, 1), " (", max_vif_poly_var, ")"),
f3(max_vif_c, 2),
fmt_p(p_joint), fmt_p(p_quad),
paste0("λ = ", lambda_demo, ": ", f3(rmse_ridge, 3), " vs ", f3(rmse_ols, 3)))
) |> brand_table("Key results of this exercise")
```
| Remedy | When to consider it | Main risk |
|---|---|---|
| **Drop a variable** | It is economically redundant and its contribution is not significant | Omitted-variable bias if it was relevant |
| **Log transform** | Theory or the data support a multiplicative or percentage relationship | Changes the functional form; VIF need not fall |
| **Centre a polynomial** | The collinearity comes from using $x$ and $x^2$ | Only re-parametrises; adds no information |
| **Ridge regression** | The goal is prediction and coefficients are unstable | Biased; no standard t-tests; needs a chosen $\lambda$ |
| **More informative data** | The sample lacks independent variation | More rows do not help if the new rows move together too |
::: {.callout-tip}
## Take-home message
With fixed $\mathbf X$ and $E(\mathbf u)=0$, OLS is unbiased even under imperfect multicollinearity, but individual coefficients may be **imprecise**. In Sudan's short annual series, `r if (max_vif_base < 5) "the baseline regressors are not seriously collinear; the real problem appears only when the quadratic term is added" else "even the baseline regressors show collinearity, partly because of common trends"`. Treat the cure with care: a remedy must not create a worse problem (specification error).
:::
# Short tasks:
```{r}
#| label: task-map
data.frame(
Task = c("1. Manual VIF from auxiliary regressions",
"2. VIF before/after centring; why R² does not change",
"3. Is the quadratic term needed? (F-test and why p is not enough)",
"4. Change the ridge λ grid; why higher λ is not always better",
"5. High multicollinearity versus specification error"),
`Where answered` = c("Task 1 below", "Task 2 below", "Task 3 below", "Task 4 below", "Task 5 below"),
Status = "Done", check.names = FALSE
) |> brand_table("Checklist of the short tasks")
```
## Task 1: VIF by hand
For each baseline regressor we run the auxiliary regression on the remaining ones and compute $VIF_j=1/(1-R_j^2)$.
```{r}
#| label: task1
aux_r2 <- sapply(regressors, function(v) {
f <- reformulate(setdiff(regressors, v), response = v)
summary(lm(f, data = udaje8))$r.squared
})
vif_manual <- 1 / (1 - aux_r2)
vif_car <- car::vif(m_base)[regressors]
data.frame(Variable = regressors, `Auxiliary R²` = aux_r2, `VIF (manual)` = vif_manual,
`VIF (car::vif)` = as.numeric(vif_car), check.names = FALSE) |>
brand_table("Manual VIF versus car::vif()", 4)
max_diff_vif <- max(abs(vif_manual - vif_car))
```
::: {.callout-note}
## Interpretation
The largest difference between the manual and the `car::vif()` values is `r formatC(max_diff_vif, format = "e", digits = 1)`, so they agree up to rounding error. The VIF is nothing more than a transformation of the auxiliary $R^2$.
:::
## Task 2: Centring and the VIF
The before/after VIF table is in the centring section. The largest VIF changes from `r f3(max_vif_poly, 1)` to `r f3(max_vif_c, 2)`, while $R^2$ is `r f3(r2_ols, 4)` in both versions.
::: {.callout-note}
## Why VIF changes but the regression $R^2$ does not
$R^2$ describes the **overall fit**, which depends only on the space spanned by the regressors, and centring does not change that space. VIF describes the **precision of one coefficient**, which depends on how that coefficient is defined. After centring, $z$ and $z^2$ measure different things than $\ln GDP$ and $(\ln GDP)^2$, so their auxiliary regressions differ.
:::
## Task 3: Keep the quadratic term?
The decision is in the section "Remedy I". The partial F-test gives p = `r fmt_p(p_quad)`, so `r if (p_quad < 0.05) "the quadratic term should be kept" else "the quadratic term is not needed statistically"`.
::: {.callout-note}
## Why the p-value alone is not enough
(1) With severe collinearity, individual p-values are unreliable because standard errors are inflated.
(2) Statistical significance says nothing about economic relevance or functional-form theory.
(3) With about `r n8` observations, tests have low power, and "not significant" is not "no effect". The F-test should be read together with AIC/BIC, theory, and the diagnostics.
:::
## Task 4: Different ridge penalties
```{r}
#| label: task4
lambda_alt <- c(0, 0.01, 0.1, 1, 10, 100, 1000, 10000)
data.frame(
lambda = lambda_alt,
`Sum of squared std. coefficients` = sapply(lambda_alt, function(l) sum(ridge_beta(l)^2)),
`LOO-CV RMSE` = sapply(lambda_alt, loo_rmse),
check.names = FALSE
) |> brand_table("Effect of a much wider λ grid", 4)
rmse_huge <- loo_rmse(max(lambda_alt))
sd_y <- sd(y8)
```
::: {.callout-note}
## Interpretation
As $\lambda$ grows, all coefficients are pushed toward zero. At $\lambda=10{,}000$ the model approaches the constant mean, with LOO-CV RMSE `r f3(rmse_huge, 3)` against `r f3(sd_y, 3)` for the sample standard deviation of the dependent variable. A larger $\lambda$ is **not** better: it reduces variance but increases bias, so the error is U-shaped in $\lambda$ and the best value lies in between (the CV table above shows where).
:::
## Task 5: Two sentences
::: {.callout-note}
## High multicollinearity versus specification error
**High multicollinearity** means the regressors are nearly linearly dependent, so OLS remains unbiased but coefficients are estimated imprecisely (large standard errors).
A **specification error** (an omitted relevant variable, a wrong functional form or endogeneity) makes the model itself wrong, so the estimates are **biased** however precise they look.
:::
# Save the results
We save only the objects needed later.
```{r}
#| label: save-results
save(udaje8, m_base, m_nogdp, m_log, m_poly, m_poly_c,
vif_base, vif_poly, vif_poly_c, ridge_path, lambda_demo,
file = "sudan_exercise8_results.RData")
cat("Saved to sudan_exercise8_results.RData")
```
::: {.callout-tip}
## Final checklist
- [ ] Workspace restored with `load()`; sample verified
- [ ] Baseline model estimated and interpreted
- [ ] Correlation heatmap, VIF, eigenvalues and $\kappa$ interpreted
- [ ] Farrar–Glauber test reported with its caveat
- [ ] Quadratic collinearity created and diagnosed; joint F-test versus individual t-tests discussed
- [ ] Remedies I, II and III applied and interpreted
- [ ] All five short tasks answered
- [ ] No variable dropped solely because of a high VIF
:::