0

假设我想用来purrr::map创建一个模型列表,每个模型都使用不同的变量作为预测变量。我想我可以做这样的事情:

library(tidyverse)
myvars <- vars(cyl, disp, hp)
list_of_models <- map(myvars, function(x) lm(mpg ~ !!x, data = mtcars))

有人可以解释为什么这不起作用吗?

所需的输出是:

list(
lm(mpg ~ cyl, data = mtcars),
lm(mpg ~ disp, data = mtcars),
lm(mpg ~ hp, data = mtcars))
4

2 回答 2

0

这是一种不同的方法,但很容易遵循。

library(tidyverse)
library(purrr)
library(magrittr)

mtcars %>% 
 select(cyl, disp, hp) %>% 
 map(~lm(mtcars$mpg ~ .x, data = mtcars))

输出

$`cyl`

Call:
 lm(formula = mtcars$mpg ~ .x, data = mtcars)

 Coefficients:
 (Intercept)           .x  
      37.885       -2.876  


$disp

Call:
lm(formula = mtcars$mpg ~ .x, data = mtcars)

Coefficients:
 (Intercept)           .x  
     29.59985     -0.04122  


$hp

Call:
lm(formula = mtcars$mpg ~ .x, data = mtcars)

Coefficients:
 (Intercept)           .x  
     30.09886     -0.06823  

希望这可以帮助!

于 2019-08-21T21:41:24.683 回答
0

一个选项是转换为字符串,创建公式reformulate并将其传递给lm

library(rlang)
library(purrr)
out2 <- map(myvars, ~ {
       fmla <- reformulate(as_name(.x), 'mpg')
       lm1 <- lm(fmla, data = mtcars)
       lm1$call$formula <- fmla
       lm1 })

-输出

out2
#[[1]]

#Call:
#lm(formula = mpg ~ cyl, data = mtcars)

#Coefficients:
#(Intercept)          cyl  
#     37.885       -2.876  


#[[2]]

#Call:
#lm(formula = mpg ~ disp, data = mtcars)

#Coefficients:
#(Intercept)         disp  
#   29.59985     -0.04122  


#[[3]]

#Call:
#lm(formula = mpg ~ hp, data = mtcars)

#Coefficients:
#(Intercept)           hp  
#   30.09886     -0.06823  

- 检查 OP 的输出

out1 <- list(
     lm(mpg ~ cyl, data = mtcars),
      lm(mpg ~ disp, data = mtcars),
      lm(mpg ~ hp, data = mtcars))
setequal(out1, out2)
#[1] TRUE
于 2019-08-21T15:24:49.980 回答