Skip to content

Instantly share code, notes, and snippets.

@romainfrancois
Forked from DavisVaughan/zap-gapminder.r
Last active November 24, 2018 20:34
Show Gist options
  • Save romainfrancois/f2a662fcfdc04f971095fb9b0f1368b5 to your computer and use it in GitHub Desktop.
Save romainfrancois/f2a662fcfdc04f971095fb9b0f1368b5 to your computer and use it in GitHub Desktop.
library(gapminder)
library(tidyverse)
library(zap)
library(broom)
# gapminder data for Asia only
gap <- gapminder %>%
filter(continent == "Asia") %>%
mutate(yr1952 = year - 1952) %>%
mutate(country = fct_reorder2(country, .x = year, .y = lifeExp))
gap_nested <- gap %>%
group_by(country) %>%
nest()
gap_nested
#> # A tibble: 33 x 2
#> country data
#> <fct> <list>
#> 1 Afghanistan <tibble [12 × 6]>
#> 2 Bahrain <tibble [12 × 6]>
#> 3 Bangladesh <tibble [12 × 6]>
#> 4 Cambodia <tibble [12 × 6]>
#> 5 China <tibble [12 × 6]>
#> 6 Hong Kong, China <tibble [12 × 6]>
#> 7 India <tibble [12 × 6]>
#> 8 Indonesia <tibble [12 × 6]>
#> 9 Iran <tibble [12 × 6]>
#> 10 Iraq <tibble [12 × 6]>
#> # … with 23 more rows
gap_fitted <- gap_nested %>%
zap(fit = ~lm(lifeExp ~ yr1952, data = data)) %>%
zap_dfr(coef = ~tibble(!!!coef(fit)) )
gap_fitted
#> # A tibble: 33 x 4
#> country data fit coef$`(Intercept)` $yr1952
#> <fct> <list> <list> <dbl> <dbl>
#> 1 Afghanistan <tibble [12 × 6]> <S3: lm> 29.9 0.275
#> 2 Bahrain <tibble [12 × 6]> <S3: lm> 52.7 0.468
#> 3 Bangladesh <tibble [12 × 6]> <S3: lm> 36.1 0.498
#> 4 Cambodia <tibble [12 × 6]> <S3: lm> 37.0 0.396
#> 5 China <tibble [12 × 6]> <S3: lm> 47.2 0.531
#> 6 Hong Kong, China <tibble [12 × 6]> <S3: lm> 63.4 0.366
#> 7 India <tibble [12 × 6]> <S3: lm> 39.3 0.505
#> 8 Indonesia <tibble [12 × 6]> <S3: lm> 36.9 0.635
#> 9 Iran <tibble [12 × 6]> <S3: lm> 45.0 0.497
#> 10 Iraq <tibble [12 × 6]> <S3: lm> 50.1 0.235
#> # … with 23 more rows
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment