I would like to estimate many linear regressions for many groups.
I use the tidyverse, so I tried purrr's map and broom's tidy.
However, not all groups have observations for all variables in all models.
In my example below, z is missing when t is 1, so lm cannot estimate y ~ x + z when t is 1.
I thought a filter statement in each lm would solve the problem.
However, sometimes filter provides an empty data set, and lm throws an error.
I thought that map would have an option to handle these cases, but I do not see one in the help file.
Is there a best practice here? FWIW, I only want the coefficient estimates. If you swap the commented mutate the code works as expected.
library(tidyverse)
df <- tibble(t = rep(1:2, each = 10),
y = runif(20),
x = runif(20)) %>%
mutate(z = ifelse(t == 1, NA, runif(20)))
# mutate(z = runif(20))
results <- df %>%
nest(dat = -t) %>%
mutate(
model_1 = map(dat, ~ lm(y ~ x, data = .x %>% drop_na(y, x))),
model_2 = map(dat, ~ lm(y ~ x + z, data = .x %>% drop_na(x, z))),
coef_1 = map(model_1, tidy),
coef_2 = map(model_2, tidy)
) %>%
select(t, starts_with('coef')) %>%
pivot_longer(
cols = starts_with('coef')
) %>%
unnest(value)
#> Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...): 0 (non-NA) cases
Created on 2020-05-15 by the reprex package (v0.3.0)