Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
# Or we may control for the country of sampling
# This allows us to see if these relationships
# differ in certain parts of the world
lm_data_country <- data_long %>%
left_join(., gdp_per_capita[,-5], by = c("ccode", "country.name", "year")) %>%
rename(., value = value.x, gdp = value.y) %>%
group_by(country.name, variable) %>%
mutate(n = sum(!is.na(gdp))) %>%
ungroup() %>%
filter(n > 10) %>% # Require at least 10 data points
nest(-n, -country.name, -variable) %>%
mutate(fit = map(data, ~ lm(value ~ gdp, data = .)),
results = map(fit, glance)) %>%
unnest(results) %>%
select(n, variable, country.name, adj.r.squared, p.value) %>%
arrange(-adj.r.squared) %>%
filter(variable != "gdp_per_capita")
# Create labels for figure
lm_label <- lm_data_country %>%
select(n, variable) %>%
group_by(variable) %>%
summarise(n = sum(n))
# These data allow us to display the range of R^2 values
# for each country with boxplots
# Just to be cheeky let's use the same themeas Clio Infra
ggplot(data = lm_data_country, aes(x = variable, y = adj.r.squared)) +
geom_boxplot(outlier.colour = NA) +
geom_point(colour = "steelblue", alpha = 0.6, position = "jitter") +
geom_text(data = lm_label, aes(y = -0.1, label = n),
colour = "royalblue3") +
labs(y = "R^2") +
theme(axis.text.x = element_text(angle = 15))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment