Compare candidate models added or removed stepwise, then return the accepted steps, model-fit metrics, and the lowest-AIC model.
Usage
select_models(
data,
outcome,
exposures,
approach = "logit",
time = NULL,
event = NULL,
distribution = "weibull",
direction = "forward",
format = c("flextable", "gt", "tibble")
)Arguments
- data
A data frame containing the outcome and predictor variables.
- outcome
A single character string indicating the outcome variable. Quoted and bare names are accepted. Not used for survival approaches when
timeandeventare supplied.- exposures
Character vector of predictor variables to consider. Quoted names are recommended in scripts, and bare names are also accepted.
- approach
Regression method. One of:
"logit","logbinomial","poisson","robpoisson","negbin","linear","cox", or"survreg".- time, event
Survival time and event indicator for
approach = "cox"orapproach = "survreg". Quoted and bare names are accepted.- distribution
Parametric survival distribution for
approach = "survreg". One of"weibull","exponential","lognormal", or"loglogistic". Common spellings such as"log-normal"and"log-logistic"are also accepted.- direction
Stepwise selection direction. One of:
"forward"(default),"backward", or"both".- format
Output format for the viewing table. One of
"flextable"(default),"gt", or"tibble". Useformat = "tibble"to keep only the original list structure.
Value
A list with the following components:
results_table: A tibble summarising each accepted step's model metrics (AIC, BIC, deviance, log-likelihood, and adjusted R-squared for linear models).best_model: The best-fitting model object based on lowest AIC.all_models: A named list of the accepted stepwise models.direction: Stepwise selection direction used.table: A formattedgt_tblorflextablewhenformatis"gt"or"flextable".
Details
Treat stepwise selection as a screening tool. It is best used alongside the study question, clinical judgement, and model diagnostics rather than as an automatic final-model rule.
Examples
data <- data_birthwt
stepwise <- select_models(
data = data,
outcome = "bwt",
exposures = c("age", "lwt", "smoke"),
approach = "linear",
direction = "forward"
)
stepwise$results_table
#> # A tibble: 3 × 9
#> model_id formula model_terms n_predictors AIC BIC logLik deviance adj_r2
#> <int> <chr> <chr> <int> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 bwt ~ 1 Intercept … 0 3031. 3038. -1514. 1.000e8 0
#> 2 2 bwt ~ sm… smoke 1 3026. 3036. -1510. 9.63 e7 0.0311
#> 3 3 bwt ~ sm… smoke + lwt 2 3022. 3035. -1507. 9.32 e7 0.0578
stepwise$best_model
#>
#> Call:
#> stats::lm(formula = fmla, data = model_data)
#>
#> Coefficients:
#> (Intercept) smoke lwt
#> 2501.125 -272.081 4.237
#>