R - 如何将公式传递给函数内的 with(df, glm(y ~ x)) 构造

R - how to pass formula to a with(df, glm(y ~ x)) construction inside a function

我正在使用 R 中的 mice 包来乘法估算一些缺失数据。我需要能够指定传递给函数内部的 with(df, glm(y ~ x)) 结构的公式。此 with() 构造是 mice 包使用的格式,用于在 每个 估算数据集内分别拟合回归模型。

但是,我无法弄清楚阻止我成功将公式作为参数传递的作用域问题。这是一个可重现的例子:

library(mice)

data(mtcars)
mtcars[5, 5] <- NA # introduce a missing value to be imputed

mtcars.imp = mice(mtcars, m = 5)

# works correctly outside of function
with(mtcars.imp, glm(mpg ~ cyl))

fit_model_mi = function(formula) {
  with(mtcars.imp, glm(formula))
}

# doesn't work when trying to pass formula into function   
fit_model_mi("mpg ~ cyl")

另请参阅 here 以了解在 R 帮助中提出的相同问题,尽管它没有收到答案。

尝试将公式包装在 as.formula

fit_model_mi = function(formula) {
    with(mtcars.imp, glm(as.formula(formula)) )
}

似乎有效:

> fit_model_mi("mpg ~ cyl")
call :
with.mids(data = mtcars.imp, expr = glm(as.formula(formula)))

call1 :
mice(data = mtcars, m = 5)

nmis :
 mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
   0    0    0    0    1    0    0    0    0    0    0 

analyses :
[[1]]

Call:  glm(formula = as.formula(formula))

Coefficients:
(Intercept)          cyl  
     37.885       -2.876  

Degrees of Freedom: 31 Total (i.e. Null);  30 Residual
Null Deviance:      1126 
Residual Deviance: 308.3    AIC: 169.3

您还可以通过

attach您的数据
attach(mtcars)

已显示结果

fit_model_mi("mpg ~ cyl")
call :
with.mids(data = mtcars.imp, expr = glm(formula))

call1 :
mice(data = mtcars, m = 5)

nmis :
 mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
   0    0    0    0    1    0    0    0    0    0    0 

analyses :
[[1]]

Call:  glm(formula = formula)

Coefficients:
(Intercept)          cyl  
     37.885       -2.876  

Degrees of Freedom: 31 Total (i.e. Null);  30 Residual
Null Deviance:      1126 
Residual Deviance: 308.3    AIC: 169.3