Home > Blockchain >  How to use purrr to pluck/keep some elements from a list of linear regression fit objects?
How to use purrr to pluck/keep some elements from a list of linear regression fit objects?

Time:09-30

I have a list of linear regression fit objects. Let's create it in this example by:

c('hp', 'wt', 'disp') %>% 
  paste('mpg ~', .) %>% 
  map(as.formula) %>% 
  map(lm, data = mtcars)

What I would like is to keep just the residuals and fitted.values from each of the regression fit objects, within this same pipeline. I was trying to use the keep function, but it doesn't work:

c('hp', 'wt', 'disp') %>% 
  paste('mpg ~', .) %>% 
  map(as.formula) %>% 
  map(lm, data = mtcars) %>% 
  map(keep, names(.) %in% c("residuals", "fitted.values"))

Error:

Error in probe(.x, .p, ...) : length(.p) == length(.x) is not TRUE

How can I perform this action?

CodePudding user response:

If a data frame is wanted as output then use the code below or if a list is wanted omit the bind_rows line.

library(dplyr)
library(purrr)

nms <- c('hp', 'wt', 'disp')
out <- nms %>% 
  set_names(x = map(paste('mpg ~', .), as.formula)) %>% 
  map(lm, data = mtcars) %>%
  map(~ data.frame(fit = fitted(.), resid = resid(.))) %>%
  bind_rows(.id = "id")

We can simplify this slightly using sapply as it will add names and use reformulate to generate the formula.

out <- nms %>% 
  sapply(reformulate, response = "mpg") %>%
  map(lm, data = mtcars) %>%
  map(~ data.frame(fit = fitted(.), resid = resid(.))) %>%
  bind_rows(.id = "id")
  • Related