I'm working with a dataset with binary variables defining a number of different but overlapping groups (for example youth, female, certified), as well as arbitrary variables x
and y
. I'd like to run the same model for each group as well as a combined group (e.g. female AND youth).
While it's certainly not hard to copy paste the same code for each group: lm(y ~ x, data = filter(df, female == 1)
), etc for each group, I'm wondering if there's a way to do this similar to the Many Models approach in R4DS?
Hopefully this reprex helps:
library(dplyr)
library(tidyr)
library(tibble)
# Make data
df <- data.frame(
x = rnorm(5),
y = rnorm(5),
female = c(0, 0, 1, 1, 0),
youth = c(1, 0, 1, 0, 1),
certified = c(0, 0, 1, 0, 1)
) %>% as.tibble()
df
#> # A tibble: 5 x 5
#> x y female youth certified
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 0.6404664 0.4630325 0 1 0
#> 2 1.1642970 0.2696488 0 0 0
#> 3 0.1881423 0.9081086 1 1 1
#> 4 -0.4378891 -1.7633724 1 0 0
#> 5 1.1185876 0.3726534 0 1 1
# nest
df.nested <- df %>%
nest(-female, -youth, -certified)
# So I want to fit a model on each group (female, youth, certified), as well as
# an overlapping group (female AND youth).
# Can this be done without copy-pasting for each group?
female_model <- df.nested %>%
filter(female == 1) %>%
unnest() %>%
lm(y ~ x, data = .)
youth_model <- df.nested %>%
filter(youth == 1) %>%
unnest() %>%
lm(y ~ x, data = .)
certified_model <- df.nested %>%
filter(certified == 1) %>%
unnest() %>%
lm(y ~ x, data = .)
femaleXyouth_model <- df.nested %>%
filter(female == 1,
youth == 1) %>%
unnest() %>%
lm(y ~ x, data = .)
# Ideally I'd end up with a tibble something like this, where model contains the
# lm object for each group
as_tibble(list(
model = list(
female_model,
youth_model,
certified_model,
femaleXyouth_model),
group = c("female", "youth", "certified", "femaleXyouth"),
date = Sys.Date()))
#> # A tibble: 4 x 3
#> model group date
#> <list> <chr> <date>
#> 1 <S3: lm> female 2017-10-03
#> 2 <S3: lm> youth 2017-10-03
#> 3 <S3: lm> certified 2017-10-03
#> 4 <S3: lm> femaleXyouth 2017-10-03