Skip to content

Instantly share code, notes, and snippets.

@andrewheiss
Created September 20, 2023 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewheiss/30997f4511a910587343e68562074d4c to your computer and use it in GitHub Desktop.
Save andrewheiss/30997f4511a910587343e68562074d4c to your computer and use it in GitHub Desktop.
library(tidyverse)
library(palmerpenguins)
library(broom)
# Get rid of missing values
penguins <- penguins %>% drop_na(sex)
# Scatterplot
ggplot(penguins, aes(x = bill_length_mm, y = body_mass_g)) +
geom_point() +
geom_smooth(method = "lm")
# Model with one slider (bill length)
model_simple <- lm(body_mass_g ~ bill_length_mm, data = penguins)
tidy(model_simple)
# A 1 mm increase in bill length is associated with an 86.8 g increase in body mass, on average
# Model with one switch (species)
model_2 <- lm(body_mass_g ~ bill_length_mm + species + flipper_length_mm, data = penguins)
results <- tidy(model_2, conf.int = TRUE)
results
# Holding bill length and flipper length constant, Chinstrap penguins are 732 g lighter than Adelie penguins on average
# Coefficient plot for flipper length and bill length
results %>%
filter(term != "(Intercept)", !str_detect(term, "species")) %>%
ggplot(aes(x = estimate, y = term)) +
geom_pointrange(aes(xmin = conf.low, xmax = conf.high)) +
geom_vline(xintercept = 0)
# Coefficient plot for species
results %>%
filter(term != "(Intercept)", str_detect(term, "species")) %>%
ggplot(aes(x = estimate, y = term)) +
geom_pointrange(aes(xmin = conf.low, xmax = conf.high)) +
geom_vline(xintercept = 0)
# Make a binary column
penguins <- penguins %>%
mutate(is_gentoo = species == "Gentoo")
# Logistic regression
model_logit <- glm(is_gentoo ~ bill_length_mm + body_mass_g,
data = penguins,
family = binomial())
tidy(model_logit, exponentiate = TRUE, conf.int = TRUE)
# When exponentiated, all these coefficients are centered around 1 and are percents. So a 1 mm increase in bill length makes it 9% more likely to be a Gentoo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment