繁体   English   中英

有没有办法在 R 中的 glm function 中捕获变量?

[英]Is there a way of capturing variables in glm function in R?

我想将用于建模的指标变量存储到向量中,以便在 function 中使用它们。 目标是使用创建的 function 来拟合多个 model。 我尝试如下,但似乎没有做对。

# Load data (from gtsummary package)
data(trial, package = "gtsummary")

# Specify the covariates
indicatorvars <- c("trt", "grade")

# Function
modelfunc <- function(outcome, covarates) {
  glm({{outcome}} ~ {{covarates}},
      data = trial, family = binomial)

}

modelfunc("response" , "indiatorvars")

# This one works
#glm(response ~ trt + grade, data = trial, family = binomial)

您可以先将公式构建为字符串,然后再使用as.formula进行转换。 所以 function 看起来像这样:

modelfunc <- function(outcome, covarates) {
  form <- paste(outcome, "~", paste(covarates, collapse = " + "))
  glm(as.formula(form),
      data = trial, family = binomial)
  
}

这是你的例子:

modelfunc("response", indicatorvars)
#> 
#> Call:  glm(formula = as.formula(form), family = binomial, data = trial)
#> 
#> Coefficients:
#> (Intercept)    trtDrug B      gradeII     gradeIII  
#>    -0.87870      0.19435     -0.06473      0.08217  
#> 
#> Degrees of Freedom: 192 Total (i.e. Null);  189 Residual
#>   (7 observations deleted due to missingness)
#> Null Deviance:       240.8 
#> Residual Deviance: 240.3     AIC: 248.3

代表 package (v2.0.0) 于 2021 年 4 月 27 日创建

我还不喜欢这个解决方案的一点是,这个电话信息量不是很大。 所以我会稍微调整 function:

modelfunc <- function(outcome, covarates) {
  form <- paste(outcome, "~", paste(covarates, collapse = " + "))
  out <- glm(as.formula(form),
             data = trial, family = binomial)
  out$call <- out$formula # replace call with formula
  out
}

modelfunc("response", indicatorvars)
#> 
#> Call:  response ~ trt + grade
#> 
#> Coefficients:
#> (Intercept)    trtDrug B      gradeII     gradeIII  
#>    -0.87870      0.19435     -0.06473      0.08217  
#> 
#> Degrees of Freedom: 192 Total (i.e. Null);  189 Residual
#>   (7 observations deleted due to missingness)
#> Null Deviance:       240.8 
#> Residual Deviance: 240.3     AIC: 248.3

代表 package (v2.0.0) 于 2021 年 4 月 27 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM