## Individual Exercise Solution

The figure below shows the individual regression lines by country for each model. You should be able to explain what each plot says about the relationship between gross domestic savings and GDP per capita in each country.

``````library(WDI)
library(lme4)
library(tidyverse)
source('https://raw.githubusercontent.com/jayrobwilliams/RWmisc/master/theme_rw.R')

## predict.merMod doesn't like NAs
wb <- WDI(country = c('FI', 'SE', 'NO', 'DK', 'IS'),
indicator = c('NY.GDP.PCAP.KD', 'NY.GNS.ICTR.ZS'),
start = 1960, end = 2016) %>%
rename(gdp = NY.GDP.PCAP.KD, savings = NY.GNS.ICTR.ZS) %>%
na.omit()

## run models varying intercept, varying slope, and varying slope and intercept models
vi <- lmer(gdp ~  + (1 | country), data = wb)
vs <- lmer(gdp ~ (savings - 1 | country), data = wb)
vivs <- lmer(gdp ~ (savings | country), data = wb)

## predict for regression lines
wb\$fit_vi <- predict(vi)
wb\$fit_vs <- predict(vs)
wb\$fit_vivs <- predict(vivs)

## plot grouped by country, with regression lines
wb_plot_vi <- ggplot(data = wb, aes(x = savings, y = gdp, color = country)) +
geom_point(alpha = .25, size = 1.5) +
geom_line(aes(y = fit_vi)) +
labs(title = 'Varying Intercept', x = 'Gross Savings (% of GDP)', y = 'GDP per capita') +
theme_rw() +
theme(plot.title = element_text(hjust = 0.5))

wb_plot_vs <- ggplot(data = wb, aes(x = savings, y = gdp, color = country)) +
geom_point(alpha = .25, size = 1.5) +
geom_line(aes(y = fit_vs)) +
labs(title = 'Varying Slope', x = 'Gross Savings (% of GDP)', y = 'GDP per capita') +
theme_rw() +
theme(plot.title = element_text(hjust = 0.5))

wb_plot_vivs <- ggplot(data = wb, aes(x = savings, y = gdp, color = country)) +
geom_point(alpha = .25, size = 1.5) +
geom_line(aes(y = fit_vivs)) +
labs(title = 'Varying Intercept, Varying Slope', x = 'Gross Savings (% of GDP)', y = 'GDP per capita') +
theme_rw() +
theme(plot.title = element_text(hjust = 0.5))

## arrange plots into single figure
gridExtra::grid.arrange(wb_plot_vi, wb_plot_vs, wb_plot_vivs, nrow = 3)``````