I'm trying to adopt a tidy approach to fitting multiple models. I've only recently begun using purrr, so may have some naive ideas about that package. I'm trying to fit multiple models to a single data sample. I describe the models in a tibble and
map() manages to apply
lm() and store results. However, I'm clearly missing something obvious when I try to use the column of lm model objects to store predictions and residuals in my sample data frame.
MWE below. (The formulae are daft and just for illustration.)
The final line will generate results, but I'm obviously trying to avoid explicit arguments. The penultimate line generates the following error:
Error in UseMethod("predict") : no applicable method for 'predict' applied to an object of class "list"
library(modelr) library(tidyverse) tblModel <- tibble( ModelName = c('drat + wt', '0 + drat + wt', 'hp + disp') , Formula = paste('mpg ~ ', ModelName) ) %>% mutate( Model = map(Formula, lm, data = mtcars) ) tblPredictions <- modelr::gather_predictions(mtcars, tblModel$Model) tblPredictions <- modelr::gather_predictions(mtcars, tblModel$Model[], tblModel$Model[])