Fit a different model for each row of a list-columns data frame

后端 未结 2 2026
误落风尘
误落风尘 2021-01-13 10:25

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

2条回答
  •  离开以前
    2021-01-13 11:09

    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)
    

提交回复
热议问题