Applied econometrics in R: from Monte Carlo simulation to model selection
By Denis Solís Salinas
For my econometrics coursework in the winter semester 2024/2025 (module W4479, applied economics project with R), I worked through a three-part project that goes from a Monte Carlo study of ordinary least squares (OLS) all the way to modelling a curved, nonlinear relationship between GDP per capita and life expectancy. The project had to show not just that I can run lm() in R, but that I understand sampling distributions, the central limit theorem, hypothesis tests, confidence intervals and model selection. This article walks through what I did, the code I wrote and the results, with the full source on GitHub.
The three problems build on each other:
- A Monte Carlo study asking whether OLS estimates stay normal when the error term is not normal.
- A simple linear regression of household consumption on GDP for Germany.
- Model selection for a clearly nonlinear relationship between income and life expectancy.
Setup and tools
The whole project runs in R. The packages I used are dplyr for data wrangling, ggplot2 for plotting and ggpubr to arrange multi-panel figures. Data comes from the World Bank World Development Indicators, exported to CSV and read with read.csv() using sep = ";" because the exports use a semicolon delimiter.
The scripts run as RStudio files, which is why Problem 2 and 3 start with this line to make relative file paths resolve to the script folder:
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
You can drop that line if you run from a plain R session in the right working directory.
Monte Carlo study of OLS
does the distribution of OLS estimates behave as theory predicts when the errors are normal versus when they are not? I simulated a population of 1000 observations, drew samples of size 35, 120 and 500, and repeated each draw 1000 times, recording the intercept and slope each time.
The simulation setup
The course provided a helper function (with a random seed). The data generating process is a simple linear model
$$Y = 3.4 + 0.65X + u$$
with X uniform on [0, 250] and the error term drawn either from a normal distribution or from a standardized chi-squared distribution (skewed and heavy tailed):
n <- c(35, 120, 500) # sample sizes
N <- 1000 # population size
M <- 1000 # Monte Carlo repetitions
# standardized chi-squared errors (mean 0, sd 6), skewed and heavy tailed
rchisq_dm <- function(n, df, mean = 0, sd = 1) {
(rchisq(n = n, df = df) - df) / sqrt(2 * df) * sd + mean
}
set.seed(MatrNr)
X_pop <- runif(N, 0, 250)
u_norm <- rnorm(N, sd = 6)
Y_norm <- 3.4 + 0.65 * X_pop + u_norm
For each sample size and each error distribution I fit lm() M times and stored the two coefficients, exactly as you see in the loop over j.
Means and variances of the estimates
results_1a <- sim_df %>%
group_by(Number.of.Observations, Error.Function) %>%
summarise(
mean_intercept = mean(Intercept),
var_intercept = var(Intercept),
mean_slope = mean(Slope),
var_slope = var(Slope),
.groups = "drop"
)
The key finding is that the estimates stay approximately unbiased: the slope means sit near the true 0.65 across all settings, and the intercept means hover around the true 3.4. What changes with the sample size is the variance, which collapses as n grows, the consistency of OLS at work. The chi-squared errors only distort the estimates materially at the smallest sample size, where skew matters most.
Q-Q plots of the estimates
For each combination I built a 2 by 2 panel of Q-Q plots for the intercept and slope under both error distributions:
plot_int_normal <- ggplot(sub_data_normal, aes(sample = Intercept)) +
stat_qq(color = "black") +
stat_qq_line(color = "red") +
labs(title = paste("Intercept - Normal\nn =", n_val),
x = "Theoretical Quantiles", y = "Sample Quantiles")
The story is visually clear. With normal errors the points hug the red reference line at every sample size. With chi-squared errors they bow away from the line at the tails for n = 35, still visibly off for n = 120, and by n = 500 they pull back toward the diagonal. That is the central limit theorem doing exactly what the textbooks promise.
Jarque-Bera tests
Rather than trust the eye, I wrote a small Jarque-Bera function (skewness and kurtosis based, ~chi-squared with 2 degrees of freedom under the null) and ran it for every parameter, sample size and error combination:
JB_test <- function(x, alpha = 0.05) {
x_c <- x - mean(x)
n <- length(x_c)
S <- (1 / n) * sum(x_c^3) / ((1 / n) * sum(x_c^2))^1.5 # skewness
K <- (1 / n) * sum(x_c^4) / ((1 / n) * sum(x_c^2))^2 # kurtosis
JB <- n / 6 * (S^2 + (K - 3)^2 / 4) # statistic
p_value <- 1 - pchisq(JB, df = 2)
reject <- (p_value < alpha)
return(list(JB_stat = JB, p_value = p_value, reject = reject))
}
The formal test matches the plots:
- Normal errors: never rejected at any sample size, for either parameter.
- Chi-squared errors, n = 35: both intercept and slope rejected as normal.
- Chi-squared errors, n = 120: intercept still rejected; slope becomes borderline (p around 0.07, not rejected at 5%).
- Chi-squared errors, n = 500: neither rejected, normality restored.
The Jarque-Bera results, with a 5% critical value of 5.9914 for a chi-squared test with 2 degrees of freedom:
| n | error | parameter | JB statistic | p-value | reject at 5% |
|---|---|---|---|---|---|
| 35 | Normal | Intercept | 2.9825 | 0.2251 | No |
| 35 | Normal | Slope | 0.0219 | 0.9891 | No |
| 35 | chi-squared | Intercept | 26.8572 | 0.0000015 | Yes |
| 35 | chi-squared | Slope | 7.9158 | 0.0191 | Yes |
| 120 | Normal | Intercept | 1.8626 | 0.3940 | No |
| 120 | Normal | Slope | 1.2299 | 0.5406 | No |
| 120 | chi-squared | Intercept | 12.1295 | 0.0023 | Yes |
| 120 | chi-squared | Slope | 5.3130 | 0.0702 | No |
| 500 | Normal | Intercept | 0.3719 | 0.8303 | No |
| 500 | Normal | Slope | 3.1421 | 0.2078 | No |
| 500 | chi-squared | Intercept | 0.2041 | 0.9029 | No |
| 500 | chi-squared | Slope | 0.9097 | 0.6345 | No |
With normal errors the OLS estimates look normal even at small samples. With non-normal errors you get clear departures from normality at small n, and those vanish as n grows. That is the takeaway: OLS is consistent and asymptotically normal under standard assumptions, but in small samples a heavily skewed, heavy tailed error distribution can push the sampling distribution of the estimators away from normal, and the intercept is the more sensitive of the two.
Simple linear regression of consumption on GDP
Now real data. The question: how tightly does household consumption track GDP in Germany, and can I interpret and test the estimated coefficients?
The data
I read the World Bank export and set both series into billions of constant 2015 US dollars:
data <- read.csv("P_Data_Extract_From_World_Development_Indicators.csv", sep = ";")
data <- data %>% filter(!is.na(Households_consumption_expenditure), !is.na(GDP))
data$Households_consumption_expenditure_Billions <- data$Households_consumption_expenditure / 1e9
data$GDP_Billions <- data$GDP / 1e9
The resulting sample has 54 annual observations for Germany. The descriptive table shows GDP is the more volatile of the two: a variance of about 504,318 versus about 111,737 for consumption, with consumption remaining a consistently large share of GDP, as you would expect.
Fit the model
model <- lm(Households_consumption_expenditure_Billions ~ GDP_Billions, data = data)
summary(model)
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 203.7 22.2 9.178 1.84E-12 ***
GDP_Billions 0.467 0.00821 56.903 < 2e-16 ***
Multiple R-squared: 0.9842, Adjusted R-squared: 0.9839
Residual standard error: 42.43 on 52 degrees of freedom
F-statistic: 3238 on 1 and 52 DF, p-value: < 2.2e-16
The fitted model is
Household consumption expenditure = 203.7 + 0.467 GDP
plot <- ggplot(data, aes(x = GDP_Billions, y = Households_consumption_expenditure_Billions)) +
geom_point(aes(shape = "1"), color = "black", size = 3) +
geom_smooth(aes(linetype = "1"), method = "lm", formula = y ~ x,
se = FALSE, color = "red") +
labs(title = "Household Consumption Expenditure in Relation to GDP in Germany",
x = "GDP", y = "Households consumption expenditure")
The red line tracks the data closely. The R-squared of 0.9842 says about 98.4% of the variation in consumption is accounted for by GDP, and the residuals (residual standard error 42.43 billion) are small and patternless.
Interpreting the coefficients
The slope of 0.467 means each extra 1 billion in GDP is associated with an expected 0.467 billion (roughly 467 million) increase in household consumption, in constant 2015 dollars. That is economically sensible: higher national income supports more household spending (Mankiw, 2020).
The intercept of 203.7 is the predicted consumption when GDP is zero. It is mathematically defined but not practically meaningful, because a GDP of zero means no economic activity at all, so I read it as a model artifact rather than a real quantity.
Confidence intervals
Using a critical t value with 52 degrees of freedom, the approximate 99% confidence intervals are:
Lower Bound (0.005) Estimate Upper Bound (0.995)
Intercept (B1) 144.38 203.72 263.07
Slope (B2) 0.4450 0.4670 0.4889
So with high confidence the marginal effect of 1 billion in GDP on consumption lies roughly between 0.445 and 0.489 billion.
One-tailed hypothesis test
Because economic theory predicts a positive effect, I tested a one-sided alternative:
$$H0: slope <= 0$$ versus $$H1: slope > 0$$
t_value <- b2 / se.b2
critical_t <- qt(0.95, df) # one-tail critical value
p_value_test <- pt(t_value, df, lower.tail = FALSE)
The computed t value is 56.9, far above the critical value of about 1.67, with a p value effectively zero (8.19e-49). I reject the null and conclude GDP positively and significantly affects household consumption.
Modelling a nonlinear relationship
GDP per capita and life expectancy across countries is visibly curved: life expectancy rises steeply at low incomes and flattens off at high incomes. A straight line does a bad job, so the question is which transformation linearizes the relationship best.
The data
Two World Bank indicators for 2019 across 200 countries:
- GDP per capita in constant 2015 US dollars (NY.GDP.PCAP.KD).
- Life expectancy at birth in total years (SP.DYN.LE00.IN).
I loaded the cleaned export and dropped rows with missing values:
mydata <- read.csv("clean_data.csv", sep = ";", header = TRUE)
mydata <- mydata %>% filter(!is.na(GDP), !is.na(LifeExp))
Plotting life expectancy against GDP per capita shows a strong funnel: points cluster in the low income region and fan out with a steep rise, then flatten. The linear fit underperforms in the high GDP region and the growing spread of residuals hints at heteroscedasticity. A single straight line cannot capture the curve.
Testing transformations
I compared four transformed scatterplots against the raw data:
# 1) LifeExp on log(GDP)
ggplot(mydata, aes(x = log(GDP), y = LifeExp)) + geom_point(alpha = 0.25) +
geom_smooth(method = "lm", se = FALSE, color = "red")
# 2) LifeExp on 1/GDP
# 3) log(LifeExp) on GDP
# 4) log(LifeExp) on log(GDP)
The log(GDP) and log-log panels straighten the relationship, while the inverse and log-response panels stay curved.
Fitting all five models and comparing
m1 <- lm(Y ~ X, data = mydata)
m2 <- lm(Y ~ X_star, data = mydata) # X* = log(X)
m3 <- lm(Y ~ X_starstar, data = mydata) # X** = 1/X
m4 <- lm(Y_star ~ X, data = mydata) # Y* = log(Y)
m5 <- lm(Y_star ~ X_star, data = mydata) # log-log
I collected the estimates, standard errors, t values and R-squared for each into one table:
| Model | R-squared | Interpretation |
|---|---|---|
| (X, Y) | 0.434 | straight line on raw data |
| (logX, Y) | 0.717 | log income linearizes |
| (1/X, Y) | 0.482 | inverse, less effective |
| (X, logY) | 0.402 | logging response alone helps least |
| (logX, logY) | 0.697 | log-log, slope is an elasticity |
The log specifications clearly dominate: log(GDP) alone lifts R-squared from 0.43 to 0.72.
The elasticity interpretation
In the log-log model the slope is an elasticity. A slope of 0.0619 means a 1% rise in GDP per capita is associated with about a 0.062% increase in life expectancy on the fitted relationship. Because the response is logged, I exponentiate predicted values to return to the original scale when comparing models (I did this for m4 and m5 in the next step).
Picking the best model by RSS
Because m4 and m5 predict on a log scale, I exponentiated their fitted values to compare all models on the original life-expectancy scale, then summed squared residuals:
mydata$yhat_m4 <- exp(predict(m4)) # back to original Y scale
RSS_m4 <- sum((mydata$Y - mydata$yhat_m4)^2)
m1 (X, Y) 6296.955
m2 (logX, Y) 3148.747
m3 (1/X, Y) 5757.771
m4 (X, logY) 6630.757
m5 (logX, logY) 3225.215
Model 2, life expectancy on log(GDP), wins with the smallest residual sum of squares (about 3149), with the log-log model close behind.
All fitted lines on the original scale
ggplot() +
geom_point(data = mydata, aes(x = X, y = Y), color = "gray40") +
geom_line(data = df_lines, aes(x = X, y = Y_hat, color = Model)) +
scale_color_manual(values = c("red", "blue", "green", "purple", "orange"))
The raw linear model (red) is visibly wrong in the high GDP region, while the curves using log income bend to follow the data.
Prediction intervals for the best model
Choosing model 2, I computed 95% prediction intervals and overlaid them on the data:
pred_int <- predict(best_model, interval = "prediction", level = 0.95)
ggplot(mydata_sorted, aes(x = X)) +
geom_point(aes(y = Y, color = "Data"), shape = 16) +
geom_line(aes(y = fit_m2, color = "Fitted Line"), size = 1.2) +
geom_line(aes(y = lwr_m2, color = "95% Pred. Interval"), linetype = "dashed") +
geom_line(aes(y = upr_m2, color = "95% Pred. Interval"), linetype = "dashed")
The intervals are tight in the densely populated middle of the income range and widen at the extremes where data are scarce, which is exactly the uncertainty pattern you expect.
The takeaway
This project took me from simulating OLS to carrying a model selection all the way through. The through line is that OLS is consistent and asymptotically normal, that in small samples non-normal errors can break the normality of the estimates, and that the central limit theorem repairs it as the sample grows. On real data, logging a badly skewed regressor turned a poor straight line into a well-fitting, interpretable model. These were coursework exercises on observational data; a better statistical fit does not establish causation, and I present the results as documented coursework output, not as causal estimates or validated forecasts.
Tools: R, dplyr, ggplot2, ggpubr, plus World Bank data downloaded January 2025.