【问题标题】:R - how to pass formula to a with(df, glm(y ~ x)) construction inside a functionR - 如何将公式传递给函数内部的 with(df, glm(y ~ x)) 构造
【发布时间】:2016-07-30 04:07:38
【问题描述】:

我正在使用 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 帮助上提出的相同问题,尽管它没有收到答案。

【问题讨论】:

  • "mpg ~ cyl" 不是公式对象。它只是一个字符值 此外,with 函数只能在控制台级别安全使用。特别建议不要在函数内部使用它。

标签: r r-mice


【解决方案1】:

尝试将公式包装在 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

【讨论】:

    【解决方案2】:

    您也可以通过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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 2012-06-07
      • 2012-01-12
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多