---
title: "Linear Regression Specification Errors in Sudan's Renewable-Energy Model"
subtitle: "Econometrics Exercise #9 | Omitted Variables, GETS, Functional Form and RESET"
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
warning: false
message: 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("broom", "dplyr", "ggplot2", "knitr", "kableExtra", "lmtest", "MASS")
missing_packages <- required_packages[
!vapply(required_packages, requireNamespace, logical(1), quietly = TRUE)
]
if (length(missing_packages)) {
stop("Install missing packages: ", paste(missing_packages, collapse = ", "))
}
library(broom)
library(dplyr)
library(ggplot2)
library(knitr)
library(kableExtra)
library(lmtest)
brand <- "#AA272F"
brand_dark <- "#7F1D24"
brand_blue <- "#1B4F72"
brand_green <- "#477A63"
brand_amber <- "#B7791F"
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)
}
fmt_p <- function(p) ifelse(is.na(p), "—",
ifelse(p < 0.001, "< 0.001", sprintf("%.3f", p)))
fnum <- function(x, d = 3) formatC(x, format = "f", digits = d)
sig_label <- function(p) ifelse(p < .01, "strong evidence (1%)",
ifelse(p < .05, "evidence (5%)",
ifelse(p < .10, "weak evidence (10%)", "limited evidence")))
coef_table <- function(model) {
broom::tidy(model, conf.int = TRUE) |>
transmute(Term = term, Estimate = estimate, `Std. error` = std.error,
`t statistic` = statistic, `p-value` = fmt_p(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-squared` = g$r.squared,
`Adjusted R-squared` = g$adj.r.squared, `Residual SD` = g$sigma,
`F statistic` = g$statistic, `p(F)` = fmt_p(g$p.value),
AIC = g$AIC, BIC = g$BIC, check.names = FALSE)
}))
}
nested_table <- function(restricted, unrestricted) {
a <- anova(restricted, unrestricted)
data.frame(Comparison = c("Restricted", "Unrestricted"),
`Residual df` = a$Res.Df, RSS = a$RSS, `Added df` = a$Df,
`RSS reduction` = a$`Sum of Sq`, F = a$F, `p-value` = fmt_p(a$`Pr(>F)`),
check.names = FALSE)
}
```
# Exercise overview
::: {.callout-note}
## What this exercise investigates
This exercise applies the specification-error workflow to Sudan's annual renewable-energy data:
1. Compare a baseline and an extended model to assess sensitivity to omitted controls;
2. Use a simplified, transparent AIC-based general-to-specific (GETS) procedure;
3. Test whether a centered quadratic term improves the functional form;
4. use Ramsey's RESET and residual plots as complementary diagnostics;
5. Compare candidate models without treating fit statistics as proof of a correct or causal model.
The dependent variable is `REN_ERG_CONS`. The baseline uses `FDI_GDP`, `logGDP`, and `NODA_RCV`; the extended model adds `IND_VA_GDP` and `Trade_GDP`.
:::
# Data preparation and common sample
## Load the Exercise 8 data
The preferred input is the saved Exercise 8 object `udaje8`. To avoid silently loading a different or stale dataset, this document searches only for the expected Exercise 8 workspace. If it is unavailable, stop and load the correct Sudan data explicitly rather than automatically selecting an unrelated older workspace.
```{r}
#| label: load-data
workspace_candidates <- c("sudan_exercise8_results.RData", "pamat_cvicenie8.Rdata")
workspace_file <- workspace_candidates[file.exists(workspace_candidates)][1]
if (is.na(workspace_file)) {
stop("Place the correct Exercise 8 workspace in the project and name it ",
"'sudan_exercise8_results.RData' or 'pamat_cvicenie8.Rdata'.")
}
load_env <- new.env(parent = baseenv())
load(workspace_file, envir = load_env)
if (!exists("udaje8", envir = load_env, inherits = FALSE)) {
stop("The selected workspace does not contain 'udaje8'. Check the saved object.")
}
udaje8 <- get("udaje8", envir = load_env)
```
## Define and freeze the analysis sample
All model comparisons below use the same complete, finite observations. This is important for nested-model F-tests and for comparing information criteria.
```{r}
#| label: freeze-sample
candidate_vars <- c("REN_ERG_CONS", "FDI_GDP", "logGDP",
"IND_VA_GDP", "NODA_RCV", "Trade_GDP")
stopifnot(is.data.frame(udaje8),
all(candidate_vars %in% names(udaje8)),
all(vapply(udaje8[candidate_vars], is.numeric, logical(1))))
udaje9 <- udaje8 |>
select(all_of(candidate_vars)) |>
filter(if_all(everything(), ~ is.finite(.x))) |>
as.data.frame()
if (nrow(udaje9) <= length(candidate_vars) + 5) {
stop("Too few complete observations for the planned specifications.")
}
stopifnot(all(udaje9$REN_ERG_CONS >= 0),
all(udaje9$logGDP == udaje9$logGDP))
n9 <- nrow(udaje9)
data.frame(Item = c("Country", "Workspace", "Analysis sample",
"Complete observations", "Outcome"),
Value = c("Sudan (SDN)", workspace_file, "udaje9",
as.character(n9), "REN_ERG_CONS")) |>
brand_table("Sample definition")
```
::: {.callout-warning}
**Check the scale before interpreting.** The interpretations below are based on that the `REN_ERG_CONS` is recorded in percentage points or as a percentage-valued index. `logGDP` is the natural logarithm of positive GDP measured consistently across years.
:::
# Omitted-variable analysis: baseline versus extended model
## Why omission can bias coefficients
Suppose the relevant model is
$$
\mathbf y=\mathbf X\boldsymbol\beta+\mathbf u,
\qquad E(\mathbf u)=\mathbf0.
$$
If the regression omits \(\mathbf Z\), the restricted OLS estimator satisfies
$$
\boxed{
E(\widetilde{\boldsymbol{\beta}}) - \boldsymbol{\beta} =
(\mathbf{X}^{\mathsf{T}}\mathbf{X})^{-1}\mathbf{X}^{\mathsf{T}}\mathbf{Z}\boldsymbol{\gamma}.
}
$$
Leaving out $\mathbf{Z}$ systematically distorts (**biases**) our estimated coefficients **only if two conditions occur simultaneously**:
1. **The omitted variables genuinely matter** for renewable energy consumption ($\boldsymbol{\gamma} \neq \mathbf{0}$).
2. **The omitted variables move together with the included variables** ($\mathbf{X}^{\mathsf{T}}\mathbf{Z} \neq \mathbf{0}$).
Therefore, watching a coefficient shift noticeably after we add new control variables acts as a **sensitivity signal**. It warns us that the baseline estimate was picking up variation from correlated controls, though by itself it does not prove which specification represents the true causal structure.
::: {.callout-note}
## What happens if we add an unnecessary variable instead?
Including an irrelevant variable whose true effect is zero ($\gamma = 0$) **does not bias** our slope estimates under the classical assumptions—on average, they remain centered on the true values. However, if that extra variable is correlated with the other regressors, it makes the estimates **noisier** (inflating standard errors and widening confidence intervals), which makes it harder to detect statistically significant effects. (Note: the simple variance-inflation factor $1/(1-r_{xz}^2)$ from the lecture applies specifically to a two-regressor case; in larger models with several controls, the general $\text{VIF}_j = 1/(1-R_j^2)$ captures the full multi-variable correlation.)
:::
## Estimate the two specifications
\begin{aligned}
\text{Baseline: } REN_t &= \beta_0+\beta_1FDI_t+\beta_2\log GDP_t+\beta_3ODA_t+u_t,\\
\text{Extended: } REN_t &= \beta_0+\beta_1FDI_t+\beta_2\log GDP_t+\beta_3ODA_t\\
&\quad+\gamma_1Industry_t+\gamma_2Trade_t+u_t.
\end{aligned}
```{r}
#| label: omitted-models
m9_base <- lm(REN_ERG_CONS ~ FDI_GDP + logGDP + NODA_RCV, data = udaje9)
m9_ext <- lm(REN_ERG_CONS ~ FDI_GDP + logGDP + NODA_RCV +
IND_VA_GDP + Trade_GDP, data = udaje9)
brand_table(coef_table(m9_base), "Baseline OLS estimates", 4)
brand_table(coef_table(m9_ext), "Extended OLS estimates", 4)
```
## Interpret coefficient stability
```{r}
#| label: coefficient-stability
tb <- broom::tidy(m9_base) |>
select(term, estimate_base = estimate, se_base = std.error) |>
inner_join(broom::tidy(m9_ext) |>
select(term, estimate_ext = estimate, se_ext = std.error), by = "term") |>
mutate(`Change in estimate` = estimate_ext - estimate_base,
`Absolute change relative to baseline (%)` =
ifelse(abs(estimate_base) > 1e-8,
100 * (estimate_ext - estimate_base) / abs(estimate_base), NA_real_),
`SE ratio (extended / baseline)` = se_ext / se_base) |>
select(Term = term, `Baseline estimate` = estimate_base,
`Extended estimate` = estimate_ext, `Change in estimate`,
`Relative change (%)` = `Absolute change relative to baseline (%)`,
`Baseline SE` = se_base, `Extended SE` = se_ext,
`SE ratio` = `SE ratio (extended / baseline)`)
brand_table(tb, "Coefficient and standard-error stability", 4)
```
::: {.callout-note}
## How to read this table
- **Change in estimate (Did adding controls change the story?):** When we control for industry (`IND_VA_GDP`) and trade (`Trade_GDP`), the estimated effect of `FDI_GDP` drops by about **31.5%** (from `1.758` to `1.205`) and `logGDP` shifts by **−18.6%** (from `−37.068` to `−43.974`). This shows that in the simpler baseline model, FDI and GDP were partly picking up the influence of industrial structure and trade openness.
- **SE ratio (Did precision improve or worsen?):** An SE ratio **below 1** means the estimate became **more precise** because the new controls reduced unexplained residual noise (for example, `FDI_GDP` improved with an SE ratio of `0.81`). An SE ratio **above 1** means precision **worsened** due to correlation with the new controls (`NODA_RCV` rose slightly to `1.14`).
- **A shift is a clue, not automatic proof of bias:** Seeing a coefficient move tells us the model is sensitive to those controls, but we only call it *omitted-variable bias* if economic theory and joint tests confirm that `IND_VA_GDP` and `Trade_GDP` genuinely belong in the model.
:::
## Joint partial F-test
The test asks whether the two added regressors ((`IND_VA_GDP`) and trade openness (`Trade_GDP`)) improve the model jointly, conditional on the baseline variables:
$$
H_0: \gamma_{\text{Industry}} = \gamma_{\text{Trade}} = 0
\qquad \text{versus} \qquad
H_1: \text{at least one } \gamma_j \neq 0.
$$
```{r}
#| label: joint-partial-f-test
a_step2 <- anova(m9_base, m9_ext)
rss_base <- a_step2$RSS[1]
rss_ext <- a_step2$RSS[2]
rss_drop <- a_step2$`Sum of Sq`[2]
f_step2 <- a_step2$F[2]
p_step2 <- a_step2$`Pr(>F)`[2]
partial_f_df <- data.frame(
Comparison = c("Restricted", "Unrestricted"),
`Residual df` = a_step2$Res.Df,
RSS = a_step2$RSS,
`Added df` = a_step2$Df,
`RSS reduction` = a_step2$`Sum of Sq`,
`F` = a_step2$F,
`p-value` = fmt_p(a_step2$`Pr(>F)`),
check.names = FALSE
)
brand_table(
partial_f_df,
"Partial F-test for industrial value added and trade",
4
)
```
::: {.callout-tip}
## How to read this test
- **RSS reduction (`` `r sprintf("%.2f", rss_drop)` ``):** Adding `IND_VA_GDP` and `Trade_GDP` reduces the unexplained residual sum of squares from `` `r sprintf("%.2f", rss_base)` `` down to `` `r sprintf("%.2f", rss_ext)` ``.
- **Statistical decision ($F = `r sprintf("%.3f", f_step2)`$, $p = `r fmt_p(p_step2)`$):** Because $p < 0.05$, we **reject $H_0$** at the 5% significance level. The two structural variables are jointly significant and together add genuine explanatory power.
- **Practical takeaway:** Leaving both variables out of the baseline model discards important information and risks omitted-variable bias, so retaining them as a group is statistically justified (subject to economic theory and further diagnostics).
:::
# General-to-specific model selection (GETS)
## General specification
The general model includes the baseline variables, the additional structural controls, and a quadratic income term. It is intentionally broad, but it should remain economically defensible.
```{r}
#| label: gets-general
udaje9$logGDP2 <- udaje9$logGDP^2
m9_general <- lm(REN_ERG_CONS ~ FDI_GDP + logGDP + logGDP2 +
IND_VA_GDP + NODA_RCV + Trade_GDP, data = udaje9)
brand_table(coef_table(m9_general), "General specification", 4)
```
## AIC-based backward elimination
The following is a **course-style simplified GETS**, not the full Hendry procedure. It selects the eligible term with the largest p-value, then removes it only if AIC falls. The linear income term is protected while the squared term remains, preserving polynomial hierarchy.
```{r}
#| label: gets-algorithm
current_model <- m9_general
accepted_models <- list("General model" = current_model)
gets_log <- list()
iteration <- 1
repeat {
current_terms <- broom::tidy(current_model) |>
filter(term != "(Intercept)")
eligible <- current_terms
if ("logGDP2" %in% eligible$term) {
eligible <- eligible |> filter(term != "logGDP")
}
if (nrow(eligible) == 0) break
candidate <- eligible |> slice_max(p.value, n = 1, with_ties = FALSE)
term_drop <- candidate$term[1]
reduced <- update(current_model, paste(". ~ . -", term_drop))
aic_now <- AIC(current_model)
aic_reduced <- AIC(reduced)
delta <- aic_reduced - aic_now
accepted <- delta < 0
gets_log[[iteration]] <- data.frame(
Iteration = iteration, `Candidate considered` = term_drop,
`Candidate p-value` = candidate$p.value[1],
`AIC before` = aic_now, `AIC after` = aic_reduced,
`Delta AIC (after - before)` = delta,
Decision = ifelse(accepted, "Drop term", "Stop; retain current model"),
check.names = FALSE
)
if (!accepted) break
current_model <- reduced
accepted_models[[paste0("After dropping ", term_drop)]] <- current_model
iteration <- iteration + 1
}
m9_final <- current_model
gets_path <- bind_rows(gets_log)
brand_table(gets_path, "GETS elimination decisions", 4)
brand_table(fit_table(accepted_models), "Accepted models along the GETS path", 4)
brand_table(coef_table(m9_final), "Final simplified GETS model", 4)
```
::: {.callout-warning}
## AIC decision rule
The stopping rule evaluates $\Delta\text{AIC} = \text{AIC}_{\text{reduced}} - \text{AIC}_{\text{current}}$. A negative value ($\Delta\text{AIC} < 0$) favors the simpler reduced model; once $\Delta\text{AIC} \ge 0$, the algorithm stops and keeps the current model. The rejected step (`- logGDP2`) is therefore excluded from the accepted path table above.
:::
::: {.callout-note}
## Interpreting the final GETS candidate
- **Surviving predictors:** All remaining terms are statistically significant at the 1% level: `Trade_GDP` has a positive association (`+0.457` percentage points per unit of trade share, $p < 0.001$), while `logGDP` (`+241.39`, $p = 0.007$) and `logGDP2` (`−37.85`, $p = 0.002$) suggest an **inverted-U** relationship between income and renewable energy share.
- **Methodological caution:** Simplified GETS finds the best model along *one* greedy elimination path, not necessarily the global optimum across all possible subsets. Furthermore, dropping `FDI_GDP` and `IND_VA_GDP` based purely on in-sample AIC does not prove their true economic effect is zero—if economic theory requires controlling for FDI or industry, we must still check residual diagnostics and functional form (Sections 5–6) before treating this as a final specification.
:::
# Functional form: linear versus centered quadratic income
## Center the log-GDP variable
Let $c_t = \ln(GDP_t) - \overline{\ln(GDP)}$ denote the mean-centered log-GDP variable. Centering shifts the reference point to the sample average and reduces correlation between the linear and squared terms, without changing the fitted quadratic curve, residuals, or $R^2$ when the model includes an intercept and both polynomial terms.
```{r}
#| label: centered-models
udaje9$centr_logGDP <- udaje9$logGDP - mean(udaje9$logGDP)
m9_lin_centr <- lm(REN_ERG_CONS ~ FDI_GDP + centr_logGDP +
IND_VA_GDP + NODA_RCV + Trade_GDP, data = udaje9)
m9_poly_centr <- lm(REN_ERG_CONS ~ FDI_GDP + centr_logGDP +
I(centr_logGDP^2) + IND_VA_GDP + NODA_RCV + Trade_GDP,
data = udaje9)
brand_table(coef_table(m9_lin_centr), "Centered linear model", 4)
brand_table(coef_table(m9_poly_centr), "Centered quadratic model", 4)
```
::: {.callout-note}
## Comparing the centered linear and quadratic estimates
- **Centering restored precision on the linear slope:** Compared with the uncentered model in Section 4.1 (where `logGDP` had $\text{SE} = 131.22$ and $p = 0.209$), `centr_logGDP` now has a tight standard error (`4.708`) and is highly significant ($p < 0.001$), while the quadratic estimate (`−28.5515`, $p = 0.118$) remains identical.
- **No significant curvature once all controls are included:** Unlike the reduced GETS specification (which dropped `FDI_GDP`, `IND_VA_GDP`, and `NODA_RCV`), here `I(centr_logGDP^2)` is **not individually significant** at the 5% level ($p = 0.118$), and including it weakens the precision of `FDI_GDP` ($p$ rises from `0.016` to `0.528`). Next, we run a formal partial $F$-test (`anova()`) to verify whether the quadratic term improves overall fit.
:::
## Test the quadratic term
```{r}
#| label: quadratic-test
a_quad <- anova(m9_lin_centr, m9_poly_centr)
f_quad <- a_quad$F[2]
p_quad <- a_quad$`Pr(>F)`[2]
brand_table(nested_table(m9_lin_centr, m9_poly_centr),
"Partial F-test: adding centered log-GDP squared", 4)
```
::: {.callout-tip}
## How to read this test
- **Hypotheses tested:** We test $H_0: \beta_2 = 0$ (the relationship with $\ln(GDP)$ is linear) against $H_1: \beta_2 \neq 0$ (quadratic curvature improves the fit).
- **Modest RSS reduction (`23.01`):** Adding `I(centr_logGDP^2)` lowers the residual sum of squares only slightly, from `195.55` down to `172.54` (`1` added degree of freedom).
- **Statistical decision ($F = 2.667$, $p = 0.118$):** Because $p > 0.05$, we **fail to reject $H_0$** at the 5% level—the quadratic term does not add statistically significant explanatory power once all controls are included, supporting the simpler linear log-GDP specification unless Ramsey's RESET test reveals remaining nonlinearity.
:::
## Interpret the marginal association
For the quadratic model,
$$
\widehat{REN}_t = \hat{\beta}_0 + \hat{\beta}_1 c_t + \hat{\beta}_2 c_t^2 + \mathbf{x}_t^{\mathsf{T}}\hat{\boldsymbol{\delta}},
\qquad
\frac{\partial \widehat{REN}_t}{\partial \ln(GDP_t)} = \hat{\beta}_1 + 2\hat{\beta}_2 c_t.
$$
A one-percent increase in GDP changes natural log GDP by approximately \(0.01\). Therefore the approximate outcome change is \(0.01\) times the marginal slope. If the outcome is percentage-valued, this change is in percentage points.
```{r}
#| label: marginal-slope-table
b1 <- unname(coef(m9_poly_centr)["centr_logGDP"])
b2 <- unname(coef(m9_poly_centr)["I(centr_logGDP^2)"])
mean_lg <- mean(udaje9$logGDP)
income_grid <- data.frame(
Position = c("25th percentile", "Sample mean", "75th percentile"),
logGDP_value = as.numeric(quantile(udaje9$logGDP, c(.25, .50, .75)))
) |>
mutate(centr_logGDP = logGDP_value - mean_lg,
`Marginal slope` = b1 + 2 * b2 * centr_logGDP,
`Approx. effect of 1% GDP increase` = .01 * `Marginal slope`)
brand_table(income_grid, "Marginal income association at selected sample positions", 4)
```
::: {.callout-note}
At the sample mean, the marginal slope equals the coefficient on centered log GDP. Away from the mean, the slope depends on the quadratic coefficient. A positive quadratic coefficient means the slope rises with income; a negative coefficient means it falls. Whether the slope is positive or negative at a particular income level must be read from the marginal-slope table—not inferred from the quadratic coefficient alone.
:::
# Ramsey RESET and residual diagnostics
## RESET test
Ramsey's RESET test augments the estimated model with the second and third powers of the fitted values ($\widehat{REN}_t^2$ and $\widehat{REN}_t^3$) to check whether nonlinearities or neglected interactions remain in the residuals:
$$
REN_t = \mathbf{x}_t^{\mathsf{T}}\boldsymbol{\beta} + \gamma_2 \widehat{REN}_t^2 + \gamma_3 \widehat{REN}_t^3 + v_t,
\qquad
H_0: \gamma_2 = \gamma_3 = 0.
$$
```{r}
#| label: marginal-slopes
b1_hat <- unname(coef(m9_poly_centr)["centr_logGDP"])
b2_hat <- unname(coef(m9_poly_centr)["I(centr_logGDP^2)"])
m_log <- mean(udaje9$logGDP)
pos_vals <- c(
`25th percentile` = unname(quantile(udaje9$logGDP, 0.25)),
`Sample mean` = m_log,
`75th percentile` = unname(quantile(udaje9$logGDP, 0.75))
)
marginal_tbl <- data.frame(
Position = names(pos_vals),
`log(GDP)` = unname(pos_vals),
`Centered log(GDP)` = unname(pos_vals) - m_log,
`Marginal slope` = b1_hat + 2 * b2_hat * (unname(pos_vals) - m_log),
`Approx. effect of +1% GDP (pp)` = 0.01 * (b1_hat + 2 * b2_hat * (unname(pos_vals) - m_log)),
check.names = FALSE
)
brand_table(marginal_tbl, "Marginal income association at selected sample positions", 4)
```
## Interpret the marginal association
In the centered quadratic specification:
$$
\widehat{REN}_t = \hat{\beta}_0 + \hat{\beta}_1 c_t + \hat{\beta}_2 c_t^2 + \mathbf{x}_{t,\text{controls}}^{\mathsf{T}}\hat{\boldsymbol{\delta}},
$$
the marginal slope with respect to $\ln(GDP_t)$ changes linearly with centered log GDP ($c_t$):
$$
\boxed{\frac{\partial \widehat{REN}_t}{\partial \ln(GDP_t)} = \hat{\beta}_1 + 2\hat{\beta}_2 c_t.}
$$
Because a 1% increase in GDP raises $\ln(GDP_t)$ by approximately $0.01$, multiplying the marginal slope by $0.01$ gives the approximate change in renewable energy consumption in **percentage points**, holding other controls constant.
::: {.callout-note}
## Reading the marginal slopes across income levels
- **At the sample mean ($c_t = 0$):** The quadratic term drops out, so the marginal slope equals $\hat{\beta}_1 = -48.36$. A 1% rise in GDP is associated with a **$-0.48$ percentage-point** change in Sudan's renewable energy share.
- **How the slope changes with income ($\hat{\beta}_2 = -28.55 < 0$):** Because the quadratic coefficient is negative, the marginal association grows steeper (more negative) as income rises—moving from **$-0.42$ pp** per 1% GDP increase at the 25th percentile to **$-0.57$ pp** at the 75th percentile.
- **Always evaluate the full slope, not $\hat{\beta}_2$ alone:** Whether the overall income association is positive or negative at a given GDP level depends on $\hat{\beta}_1 + 2\hat{\beta}_2 c_t$ together, not on the sign of $\hat{\beta}_2$ by itself (and recall from Section 5.2 that this curvature is not statistically significant at the 5% level, $p = 0.118$).
:::
# Ramsey RESET and residual diagnostics
## RESET test
Ramsey's RESET test augments the estimated model with the second and third powers of the fitted values ($\widehat{REN}_t^2$ and $\widehat{REN}_t^3$) to check whether nonlinearities or neglected interactions remain in the residuals:
$$
REN_t = \mathbf{x}_t^{\mathsf{T}}\boldsymbol{\beta} + \gamma_2 \widehat{REN}_t^2 + \gamma_3 \widehat{REN}_t^3 + v_t,
\qquad
H_0: \gamma_2 = \gamma_3 = 0.
$$
```{r}
#| label: reset-tests
reset_lin <- lmtest::resettest(m9_lin_centr, power = 2:3, type = "fitted")
reset_poly <- lmtest::resettest(m9_poly_centr, power = 2:3, type = "fitted")
extract_reset <- function(res, spec_name) {
data.frame(
Specification = spec_name,
`F statistic` = unname(res$statistic),
df1 = unname(res$parameter[1]),
df2 = unname(res$parameter[2]),
`p-value` = fmt_p(res$p.value),
`Decision (5%)` = ifelse(res$p.value < 0.05,
"Reject H0 (Misspecification flagged)",
"Do not reject H0"),
Method = res$method,
check.names = FALSE
)
}
reset_summary <- dplyr::bind_rows(
extract_reset(reset_lin, "Centered Linear (m9_lin_centr)"),
extract_reset(reset_poly, "Centered Quadratic (m9_poly_centr)")
)
brand_table(reset_summary, "Ramsey RESET Test Results (Powers 2 and 3 of Fitted Values)", 4)
```
::: {.callout-important}
- **When RESET rejects ($p < 0.05$):** It warns that the conditional mean is misspecified (via omitted nonlinearities, missing interaction terms, or a wrong functional form), **without identifying** which variable or transformation is missing.
- **When RESET fails to reject ($p \ge 0.05$):** It **does not prove causality** and **does not guarantee** the model is correctly specified—especially in a small sample ($N = 27$), where test power is limited.
:::
::: {.callout-note}
## Model-specific interpretation
- **Centered linear (`m9_lin_centr`):** $F = 6.469$, $p = 0.007 < 0.05$ — we **reject $H_0$**, flagging significant functional-form misspecification.
- **Centered quadratic (`m9_poly_centr`):** $F = 4.625$, $p = 0.024 < 0.05$ — we still **reject $H_0$**. Adding a quadratic term in $\ln(GDP)$ lowers the $F$-statistic slightly, but does **not** eliminate the underlying specification issue (which may stem from nonlinearities in other regressors such as `FDI_GDP` or `IND_VA_GDP`, or structural shifts over time).
:::
## Residual-versus-fitted plots
```{r}
#| label: residual-plots
#| fig-width: 10
#| fig-height: 4.5
old_par <- par(no.readonly = TRUE)
par(mfrow = c(1, 2))
plot(m9_lin_centr, which = 1, col = brand_blue, col.smooth = brand,
main = "Centered linear model")
plot(m9_poly_centr, which = 1, col = brand_blue, col.smooth = brand,
main = "Centered quadratic model")
par(old_par)
```
::: {.callout-note}
## Visual diagnostic assessment
- **Persistent curvature in the LOWESS line:** In the left panel (*Centered linear model*), the red LOWESS smoother rises above zero in the middle range (fitted values around `70–75`) and dips below zero at the upper tail (`80–85`). Adding `I(centr_logGDP^2)` in the right panel (*Centered quadratic model*) barely flattens this wave—matching the Ramsey RESET result ($p = 0.024$) that a quadratic income term alone does not resolve the remaining nonlinearity.
- **Large negative residuals (`2012`, `2013`, `2019`):** Both specifications show the same three prominent negative residuals (`-5` to `-7` percentage points) in `2012`, `2013`, and `2019`. These likely reflect structural shocks in Sudan's economy (such as the post-2011 South Sudan secession adjustment and the 2019 political transition) rather than simple polynomial curvature in GDP.
:::
# Compare the candidate models
The following table compares models with the same outcome and frozen sample. AIC and BIC are useful relative criteria: lower values are preferred among the models being compared, but neither proves that the model is true.
```{r}
#| label: final-model-comparison
candidate_models <- list(
"Baseline" = m9_base,
"Extended" = m9_ext,
"GETS general" = m9_general,
"GETS final" = m9_final,
"Centered linear" = m9_lin_centr,
"Centered quadratic" = m9_poly_centr
)
brand_table(fit_table(candidate_models), "Candidate model comparison", 4)
```
| Issue | Diagnostic | Practical response | Important limitation |
|:--|:--|:--|:--|
| Omitted relevant variable | Coefficient stability; partial F-test | Add theoretically justified controls | Coefficient shifts alone do not prove bias |
| Unnecessary regressor | Partial F-test; AIC/BIC; theory | Consider parsimony without automatic deletion | A high p-value alone does not establish irrelevance |
| Functional-form error | Quadratic nested test; RESET; residual plot | Test a justified transformation | RESET does not identify the correct transformation |
| Serial dependence | Breusch–Godfrey / residual ACF (not performed here) | Consider time-series specification and suitable inference | HAC standard errors do not fix a misspecified conditional mean |
# Conclusion
::: {.callout-tip}
The preferred specification should be selected by combining the partial F-test, coefficient stability, GETS/AIC path, quadratic-term test, RESET, residual plots, economic reasoning, and data limitations. Interpret each estimate in the units of the outcome and regressor. Report association rather than causation, and do not claim a specification is correct merely because its \(R^2\) is high or a diagnostic fails to reject.
:::
# Save the analysis objects
Save only the objects needed for the next exercise rather than the entire R session, which may contain unrelated data or temporary objects.
```{r}
#| label: save-workspace
save(udaje9, m9_base, m9_ext, m9_general, m9_final,
m9_lin_centr, m9_poly_centr, candidate_models,
file = "pamat_cvicenie9.Rdata")
cat("Saved Exercise 9 models and data (N =", nrow(udaje9), ").")
```