使用量化映射变量列表

时间:2019-08-21 15:22:16

标签: r purrr quosure

让我们说我想使用on_submit_do { if phone_type == "Other" && trimmed(description) == "" then alert_at_component("enter description of other phone type", description) else continue_as_normal_and_transmit_form_data_to_server end_if } 创建一个模型列表,每个模型都使用不同的变量作为预测变量。我想我可以做这样的事情:

purrr::map

有人可以解释为什么这行不通吗?

所需的输出是:

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

2 个答案:

答案 0 :(得分: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 })

-检查OP的输出

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  

答案 1 :(得分: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  

希望这会有所帮助!