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

穿精又带淫゛_ 提交于 2019-12-12 02:23:18

问题


I'm using the mice package in R to multiply-impute some missing data. I need to be able to specify a formula that is passed to a with(df, glm(y ~ x)) construction inside of a function. This with() construction is the format used by the mice package to fit the regression model separately within each of the imputed datasets.

However, I cannot figure out the scoping problems preventing me from successfully passing the formula as an argument. Here is a reproducible example:

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")

Also see here for the same question being asked on R help, although it does not receive an answer.


回答1:


Try wrapping the formula in as.formula

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

Seems to work:

> 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



回答2:


You can also attach your data by

attach(mtcars)

Result shown

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


来源:https://stackoverflow.com/questions/38670249/r-how-to-pass-formula-to-a-withdf-glmy-x-construction-inside-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!