How to loop with multiple independent variables in r with map function

Viewed 240

Just as the title.

There is an simple example.

If I want to explore the relationship between vs(dependent variable) and mpg, cyl, and disp(independent variables), respectively, I can code like this:

library(tidyverse)

mtcars <- as_tibble(mtcars) %>% 
  mutate(mpg10 = mpg*10, cyl10 = cyl*10, disp10 = disp*10)

x = c('mpg', 'cyl', 'disp')

# y ~ x style
models <- map(x, ~ lm(substitute(vs ~ i, list(i = as.name(.))), data = mtcars))

Now I want to do more further. If mpg in the model, mpg10 also should be put in. If cyl in the model, also cyl10 should be put in, etc. Like this:

# y ~ x1 + x2 style
model1 <- lm(vs ~ mpg + mpg10, data = mtcars)
model2 <- lm(vs ~ cyl + cyl10, data = mtcars)
model3 <- lm(vs ~ disp + disp10, data = mtcars)

I don't know how to do this with map() function or for loop.

Any help will be highly appreciated!

1 Answers

You can use grep to find all the column names with the same name and use reformulate to create formula to use in lm.

purrr::map(x, ~lm(reformulate(grep(.x, names(mtcars), value = TRUE), 
                'vs'), data = mtcars))
Related