1

我正在使用miceR 中的包来对一些缺失的数据进行乘法估算。我需要能够指定传递给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")

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

4

2 回答 2

3

尝试将公式包装在 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
于 2016-07-30T04:55:18.553 回答
0

您还可以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
于 2016-07-30T04:56:57.830 回答