What is the best way to fit different model formulae that vary by the row of a data frame with the list-columns data structure in tidyverse?
In R for Data Science, H
I found purrr::modify_depth() that does what I want to do with est_model()
in the original question. This is the solution I am now happy with:
library(gapminder)
library(tidyverse)
library(purrr)
library(broom)
fmlas <- tibble::tribble(
~continent, ~formula,
"Asia", ~lm(lifeExp ~ year, data = .),
"Europe", ~lm(lifeExp ~ year + pop, data = .),
"Africa", ~lm(lifeExp ~ year + gdpPercap, data = .),
"Americas", ~lm(lifeExp ~ year - 1, data = .),
"Oceania", ~lm(lifeExp ~ year + pop + gdpPercap, data = .)
)
by_continent <- gapminder %>%
nest(-continent) %>%
left_join(fmlas) %>%
mutate(model=map2(data, formula, ~modify_depth(.x, 0, .y)))
by_continent %>%
mutate(glance=map(model, glance)) %>%
unnest(glance, .drop=T)