0

I'm wondering how I can make this "tidy model" code "cleaner".

Generally I fit a model and provide predictions in one wrapper function, but sometimes I want to pass back other pieces of data from the fitting or predicting (the model itself, metadata, or fitted values, etc). It's a list that is returned. What's the tidiest way to pass this result back as additionally columns, one per element in the list (here it is yhat_fit and yhat), with piping

library(tidymodels)
y_s <- vfold_cv(mtcars, 5)

fit_model <- function(x) {

  model <- lm(mpg ~ hp, data = analysis(x))

  yhat <- predict(model, assessment(x))

  list(yhat_fit = model$fitted.values, yhat = yhat)
}

# this is a problem:
out <- y_s %>% mutate(model = map(y_s$splits, fit_model))
# # A tibble: 5 x 3
# splits         id    model     
# * <list>         <chr> <list>    
#   1 <split [25/7]> Fold1 <list [2]>
#   2 <split [25/7]> Fold2 <list [2]>
#   3 <split [26/6]> Fold3 <list [2]>
#   4 <split [26/6]> Fold4 <list [2]>
#   5 <split [26/6]> Fold5 <list [2]>

This is a solution, but I am not sure if there is a function that already exists which does this already in a cleaner way?

y_s2 <- bind_cols(y_s, as_tibble(transpose(out$model)))
# A tibble: 5 x 4
# splits         id    yhat_fit   yhat     
# <list>         <chr> <list>     <list>   
#   1 <split [25/7]> Fold1 <dbl [25]> <dbl [7]>
#   2 <split [25/7]> Fold2 <dbl [25]> <dbl [7]>
#   3 <split [26/6]> Fold3 <dbl [26]> <dbl [6]>
#   4 <split [26/6]> Fold4 <dbl [26]> <dbl [6]>
#   5 <split [26/6]> Fold5 <dbl [26]> <dbl [6]>

1 Answers1

0

This seems to be one way: convert the output (a list of stuff) to a tibble of list columns and then unnest.

fit_model2 <- function(x) {

  model <- lm(mpg ~ hp, data = analysis(x))

  yhat <- predict(model, assessment(x))

  tibble(yhat_fit = list(model$fitted.values), yhat = list(yhat))
}


out <- y_s %>% mutate(model = map(y_s$splits, fit_model2)) %>% unnest(model)

# A tibble: 5 x 4
#  splits         id    yhat_fit   yhat     
#  <list>         <chr> <list>     <list>   
#1 <split [25/7]> Fold1 <dbl [25]> <dbl [7]>
#2 <split [25/7]> Fold2 <dbl [25]> <dbl [7]>
#3 <split [26/6]> Fold3 <dbl [26]> <dbl [6]>
#4 <split [26/6]> Fold4 <dbl [26]> <dbl [6]>
#5 <split [26/6]> Fold5 <dbl [26]> <dbl [6]>