user5280725
user5280725

Reputation: 17

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

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.

Upvotes: 1

Views: 1191

Answers (2)

Agaz Wani
Agaz Wani

Reputation: 5694

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

Upvotes: 0

Philip Parker
Philip Parker

Reputation: 639

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

Upvotes: 3

Related Questions