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

后端 未结 2 513
梦毁少年i
梦毁少年i 2021-01-24 03:39

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

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-24 04:14

    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
    

提交回复
热议问题