Skip to content

Instantly share code, notes, and snippets.

@padpadpadpad
Created November 12, 2018 13:59
Show Gist options
  • Select an option

  • Save padpadpadpad/ec8ab1659daf88048c057fdeda1820a5 to your computer and use it in GitHub Desktop.

Select an option

Save padpadpadpad/ec8ab1659daf88048c057fdeda1820a5 to your computer and use it in GitHub Desktop.
# quick linear regression using broom and the tidyverse ####
# load packages
library(tidyr)
library(ggplot2)
library(dplyr)
library(broom)
library(gapminder)
library(janitor)
library(purrr)
# load dataset
data(gapminder)
# clean up names using janitor::clean_names()
d <- clean_names(gapminder)
# look at data
d %>%
glimpse()
# plot life_exp by year by continent
ggplot(d, aes(year, life_exp, col = continent)) +
geom_point() +
stat_smooth(method = 'lm', se = FALSE)
# lets fit an lm for each continent
d_mods <- group_by(d, continent) %>%
nest() %>%
mutate(., fit = purrr::map(data, ~lm(life_exp ~ year, data = .x)))
# look at first fit
d_mods$fit[[1]]
# look at model dataframe
d_mods
# get mod diagnostics - using broom::glance
mod_diags <- d_mods %>%
unnest(fit %>% map(glance))
mod_diags
# get parameters using broom::tidy
params <- d_mods %>%
unnest(fit %>% map(tidy))
params
# get preds using broom::augment
preds <- d_mods %>%
unnest(fit %>% map(augment))
# plot life_exp by year by continent
ggplot(preds, aes(year, life_exp, col = continent)) +
geom_point() +
geom_line(aes(year, .fitted))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment