Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Maintain call properties when using a regression with purrr::map

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading