R-如何将公式传递给函数内部的with(df,glm(y〜x))构造 [英] R - how to pass formula to a with(df, glm(y ~ x)) construction inside a function
问题描述
我在R中使用mice
包对一些丢失的数据进行乘法插补.我需要能够指定一个传递给函数内部with(df, glm(y ~ x))
构造的公式.这种with()
构造是mice
包使用的格式,用于分别在估算数据集的每个中拟合回归模型.
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")
另请参见此处,尽管没有收到答复,但在R帮助中询问的是同一问题.
Also see here for the same question being asked on R help, although it does not receive an answer.
推荐答案
尝试将公式包装为as.formula
Try wrapping the formula in 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
这篇关于R-如何将公式传递给函数内部的with(df,glm(y〜x))构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!