All script is copied from Hadley Wickham’s Plotcon 2016 lecture. Video Link
| country | continent | year | lifeExp | pop | gdpPercap |
|---|---|---|---|---|---|
| Afghanistan | Asia | 1952 | 28.801 | 8425333 | 779.4453 |
| Afghanistan | Asia | 1957 | 30.332 | 9240934 | 820.8530 |
| Afghanistan | Asia | 1962 | 31.997 | 10267083 | 853.1007 |
| Afghanistan | Asia | 1967 | 34.020 | 11537966 | 836.1971 |
| Afghanistan | Asia | 1972 | 36.088 | 13079460 | 739.9811 |
| Afghanistan | Asia | 1977 | 38.438 | 14880372 | 786.1134 |
by_country <- gapminder %>% group_by(continent, country) %>% nest()
# head(by_country)
by_country$data[[1]] %>% head() # Afghanistan| year | lifeExp | pop | gdpPercap | year1950 |
|---|---|---|---|---|
| 1952 | 28.801 | 8425333 | 779.4453 | 2 |
| 1957 | 30.332 | 9240934 | 820.8530 | 7 |
| 1962 | 31.997 | 10267083 | 853.1007 | 12 |
| 1967 | 34.020 | 11537966 | 836.1971 | 17 |
| 1972 | 36.088 | 13079460 | 739.9811 | 22 |
| 1977 | 38.438 | 14880372 | 786.1134 | 27 |
| year | lifeExp | pop | gdpPercap | year1950 |
|---|---|---|---|---|
| 1952 | 55.23 | 1282697 | 1601.056 | 2 |
| 1957 | 59.28 | 1476505 | 1942.284 | 7 |
| 1962 | 64.82 | 1728137 | 2312.889 | 12 |
| 1967 | 66.22 | 1984060 | 2760.197 | 17 |
| 1972 | 67.69 | 2263554 | 3313.422 | 22 |
| 1977 | 68.93 | 2509048 | 3533.004 | 27 |
models <- models %>%
mutate(
glance = model %>% map(broom::glance),
rsq = glance %>% map_dbl("r.squared"),
tidy = model %>% map(broom::tidy),
augment = model %>% map(broom::augment)
)
# models %>% arrange(desc(rsq)) %>% head()
models[sample(1:142, 15),] %>% ggplot(aes(rsq, reorder(country, rsq))) +
geom_point(aes(colour = continent))#
# models %>% unnest(data)
# models %>% unnest(glance, .drop = TRUE)
# models %>% unnest(tidy)
models %>%
unnest(tidy) %>%
select(continent, country, term, estimate, rsq) %>%
spread(term, estimate) %>%
ggplot(aes(`(Intercept)`, year1950)) +
geom_point(aes(colour = continent, size = rsq)) +
geom_smooth(se = FALSE) +
xlab("Life Expectancy (1950)") +
ylab("Yearly improvement") +
scale_size_area()## `geom_smooth()` using method = 'loess' and formula 'y ~ x'