Moses
Moses

Reputation: 1484

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

I would like to store indicator variables to be used in modelling into a vector to use them in a function. The goal is to use the created function to fit more than one model. I tried it as below but did not seem to get it right.

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

Upvotes: 2

Views: 143

Answers (1)

JBGruber
JBGruber

Reputation: 12410

You can first build up your formula as a character string before converting it using as.formula. So the function would look like this:

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

And here is your example:

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

Created on 2021-04-27 by the reprex package (v2.0.0)

What I don't yet like about this solution is that the call is not very informative. So I would slightly adapt the 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

Created on 2021-04-27 by the reprex package (v2.0.0)

Upvotes: 1

Related Questions