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

Using purrr:map2 to perform regression where the predictor and the criterion are stored in different objects

for the purposes of this question, let’s create the following setup:

mtcars %>% 
  group_split(carb) %>% 
  map(select, mpg) -> criterion

mtcars %>% 
  group_split(carb) %>% 
  map(select, qsec) -> predictor

This code will create two lists of length 6. What I want to do is to perform 6 linear regressions within each of these 6 groups. I read about the map2 function and I thought that the code should look like this:

map2(criterion, predictor, lm(criterion ~ predictor))

But that doesn’t seem to work. So in which way could this be done?

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

>Solution :

simplify2array (you need a list of vectors, not a list of data frames) and use a lambda-function with ~:

map2(simplify2array(criterion), simplify2array(predictor), ~ lm(.x ~ .y))
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