Home > OS >  Using purrr to map right-hand-side variables to regression functions
Using purrr to map right-hand-side variables to regression functions

Time:10-12

I have a large number of regression models specified by reference to right-hand-side variables, and I want to use purrr to generate a set of lists with the models. Here is an example of the desired end result using toy data:

m.1.1 <- "cyl"
m.1.2 <- paste(c(m.1.1, "disp"), collapse = "   ")


m.1.1_reg <- lm(
  data = mtcars,
  formula = as.formula(paste0("mpg ~ ", m.1.1)))


m.1.2_reg <- lm(
  data = mtcars,
  formula = as.formula(paste0("mpg ~ ", m.1.2)))

How can I achieve the same outcome (i.e., a list named m.1.1_reg and another list named m.1.2_reg) using purrr?

CodePudding user response:

Just loop over the 'm.1.' objects in map and create the formula

library(purrr)
out <- map(dplyr::lst(m.1.1, m.1.2), 
    ~ lm(data = mtcars, formula = as.formula(paste0("mpg ~ ", .x))))

-checking the names

> names(out)
[1] "m.1.1" "m.1.2"
  • Related