Suppose you have a list that contains multiple dataframes. Suppose you would like to "loop" through each of these dataframes within a regression model using purrr::map. However, you would like to maintain the names of the call$object. In the case below, you would like cars_output[[1]]$call$data to return mtcars instead of ..
library(tidyverse)
## creating a list of dataframes
cars_list <- list(mtcars, mtcars)
## iterating over each data frame within the model
cars_output <- map(cars_list,~lm(mpg ~ cyl, data = .))
## desired output would be mtcars, not .
cars_output[[1]]$call$data
>Solution :
Create a named list instead of just only values and then loop over the list with imap and modify the call$data with the names i.e. .y
library(purrr)
cars_list <- dplyr::lst(mtcars, mtcars)
cars_output <- imap(cars_list,~{
model <- lm(mpg ~ cyl, data = .x)
model$call$data <- .y
model})
-checking
> cars_output[[1]]$call$data
[1] "mtcars"