% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fullfit.R
\name{fullfit}
\alias{fullfit}
\title{Complete Regression Analysis Workflow}
\usage{
fullfit(
  data,
  outcome,
  predictors,
  method = "screen",
  multi_predictors = NULL,
  p_threshold = 0.05,
  columns = "both",
  model_type = "glm",
  family = "binomial",
  random = NULL,
  conf_level = 0.95,
  reference_rows = TRUE,
  show_n = TRUE,
  show_events = TRUE,
  digits = 2,
  p_digits = 3,
  labels = NULL,
  metrics = "both",
  return_type = "table",
  keep_models = FALSE,
  exponentiate = NULL,
  conf_method = NULL,
  parallel = TRUE,
  n_cores = NULL,
  number_format = NULL,
  verbose = NULL,
  ...
)
}
\arguments{
\item{data}{Data frame or data.table containing the analysis dataset. The 
function automatically converts data frames to data.tables for efficient
processing.}

\item{outcome}{Character string specifying the outcome variable name. For 
time-to-event analysis, use \code{Surv()} syntax for the outcome variable
(\emph{e.g.,} \code{"Surv(os_months, os_status)"}).}

\item{predictors}{Character vector of predictor variable names to analyze. 
All predictors are tested in univariable models. The subset included in 
the multivariable model depends on the \code{method} parameter.}

\item{method}{Character string specifying the variable selection strategy:
\itemize{
  \item \code{"screen"} - Automatic selection based on univariable \emph{p}-value 
    threshold. Only predictors with p \eqn{\le} \code{p_threshold} in univariable 
    analysis are included in the multivariable model [default]
  \item \code{"all"} - Include all predictors in both univariable and 
    multivariable analyses (no selection)
  \item \code{"custom"} - Manual selection. All predictors in univariable 
    analysis, but only those specified in \code{multi_predictors} are 
    included in multivariable model
}}

\item{multi_predictors}{Character vector of predictors to include in the 
multivariable model when \code{method = "custom"}. Required when using 
custom selection. Ignored for other methods. Default is \code{NULL}.}

\item{p_threshold}{Numeric \emph{p}-value threshold for automatic variable
selection when \code{method = "screen"}. Predictors with univariable
\emph{p}-value less than or equal to the threshold are included in
multivariable model. Common values: 0.05 (strict), 0.10 (moderate),
0.20 (liberal screening). Default is 0.05. Ignored for other methods.}

\item{columns}{Character string specifying which result columns to display:
\itemize{
  \item \code{"both"} - Show both univariable and multivariable results 
    side-by-side [default]
  \item \code{"uni"} - Show only univariable results
  \item \code{"multi"} - Show only multivariable results
}}

\item{model_type}{Character string specifying the regression model type:
\itemize{
  \item \code{"glm"} - Generalized linear model (default). Supports multiple 
    distributions via the \code{family} parameter including logistic, Poisson, 
    Gamma, Gaussian, and quasi-likelihood models.
  \item \code{"lm"} - Linear regression for continuous outcomes with normally 
    distributed errors.
  \item \code{"coxph"} - Cox proportional hazards model for time-to-event 
    survival analysis. Requires \code{Surv()} outcome syntax.
  \item \code{"clogit"} - Conditional logistic regression for matched 
    case-control studies.
  \item \code{"negbin"} - Negative binomial regression for overdispersed count 
    data (requires MASS package). Estimates an additional dispersion parameter 
    compared to Poisson regression.
  \item \code{"glmer"} - Generalized linear mixed-effects model for hierarchical 
    or clustered data with non-normal outcomes (requires \pkg{lme4} package and 
    \code{random} parameter).
  \item \code{"lmer"} - Linear mixed-effects model for hierarchical or clustered 
    data with continuous outcomes (requires \pkg{lme4} package and \code{random} 
    parameter).
  \item \code{"coxme"} - Cox mixed-effects model for clustered survival data 
    (requires coxme package and \code{random} parameter).
}}

\item{family}{For GLM and GLMER models, specifies the error distribution and link 
function. Can be a character string, a family function, or a family object.
Ignored for non-GLM/GLMER models.

\strong{Binary/Binomial outcomes:}
\itemize{
  \item \code{"binomial"} or \code{binomial()} - Logistic regression for binary 
    outcomes (0/1, TRUE/FALSE). Returns odds ratios (OR). Default.
  \item \code{"quasibinomial"} or \code{quasibinomial()} - Logistic regression 
    with overdispersion. Use when residual deviance >> residual df.
  \item \code{binomial(link = "probit")} - Probit regression (normal CDF link).
  \item \code{binomial(link = "cloglog")} - Complementary log-log link for 
    asymmetric binary outcomes.
}

\strong{Count outcomes:}
\itemize{
  \item \code{"poisson"} or \code{poisson()} - Poisson regression for count 
    data. Returns rate ratios (RR). Assumes mean = variance.
  \item \code{"quasipoisson"} or \code{quasipoisson()} - Poisson regression 
    with overdispersion. Use when variance > mean.
}

\strong{Continuous outcomes:}
\itemize{
  \item \code{"gaussian"} or \code{gaussian()} - Normal/Gaussian distribution 
    for continuous outcomes. Equivalent to linear regression.
  \item \code{gaussian(link = "log")} - Log-linear model for positive continuous 
    outcomes. Returns multiplicative effects.
}

\strong{Positive continuous outcomes:}
\itemize{
  \item \code{"Gamma"} or \code{Gamma()} - Gamma distribution for positive, 
    right-skewed continuous data (\emph{e.g.,} costs, lengths of stay). When
    passed as a string, resolves to log link for interpretable multiplicative
    effects.
  \item \code{Gamma(link = "inverse")} - Gamma with inverse (canonical) link.
  \item \code{Gamma(link = "identity")} - Gamma with identity link for additive 
    effects on positive outcomes.
  \item \code{"inverse.gaussian"} or \code{inverse.gaussian()} - Inverse Gaussian 
    for positive, highly right-skewed data.
}

For negative binomial regression (overdispersed counts), use 
\code{model_type = "negbin"} instead of the \code{family} parameter.

See \code{\link[stats]{family}} for additional details and options.}

\item{random}{Character string specifying the random-effects formula for 
mixed-effects models (\code{glmer}, \code{lmer}, \code{coxme}). Use standard
\pkg{lme4}/\pkg{coxme} syntax, \emph{e.g.,} \code{"(1|site)"} for random
intercepts by site, \code{"(1|site/patient)"} for nested random effects.
Required when \code{model_type} is a mixed-effects model type unless random
effects are included in the \code{predictors} vector. Alternatively, random
effects can be included directly in the \code{predictors} vector using the same 
syntax (\emph{e.g.,} \code{predictors = c("age", "sex", "(1|site)")}), though 
they will not be screened as predictors. Default is \code{NULL}.}

\item{conf_level}{Numeric confidence level for confidence intervals. Must be 
between 0 and 1. Default is 0.95 (95\% CI).}

\item{reference_rows}{Logical. If \code{TRUE}, adds rows for reference 
categories of factor variables with baseline values. Default is \code{TRUE}.}

\item{show_n}{Logical. If \code{TRUE}, includes sample size columns. 
Default is \code{TRUE}.}

\item{show_events}{Logical. If \code{TRUE}, includes events columns (survival 
and logistic models). Default is \code{TRUE}.}

\item{digits}{Integer specifying decimal places for effect estimates. 
Default is 2.}

\item{p_digits}{Integer specifying the number of decimal places for
\emph{p}-values. Values smaller than \code{10^(-p_digits)} are displayed
as \code{"< 0.001"} (for \code{p_digits = 3}), \code{"< 0.0001"} (for
\code{p_digits = 4}), etc. Default is 3.}

\item{labels}{Named character vector or list providing custom display
labels for variables. Names should match variable names, values are
display labels. Default is \code{NULL}.}

\item{metrics}{Character specification for which statistics to display:
\itemize{
  \item \code{"both"} - Show effect estimates with CI and \emph{p}-values [default]
  \item \code{"effect"} - Show only effect estimates with CI
  \item \code{"p"} - Show only \emph{p}-values
}
Can also be a character vector: \code{c("effect", "p")} is equivalent to 
\code{"both"}.}

\item{return_type}{Character string specifying what to return:
\itemize{
  \item \code{"table"} - Return formatted results table only [default]
  \item \code{"model"} - Return multivariable model object only
  \item \code{"both"} - Return list with both table and model
}}

\item{keep_models}{Logical. If \code{TRUE}, stores univariable model objects 
in the output. Can consume significant memory for many predictors. 
Default is \code{FALSE}.}

\item{exponentiate}{Logical. Whether to exponentiate coefficients. Default 
is \code{NULL}, which automatically exponentiates for logistic, Poisson,
and Cox models, and displays raw coefficients for linear models.}

\item{conf_method}{Character string controlling the confidence interval method.
If \code{NULL} (default), uses \code{getOption("summata.conf_method", "profile")}.
\itemize{
  \item \code{"profile"} - Profile likelihood intervals for GLM and negative
    binomial models (via \code{MASS::confint.glm()}), exact \emph{t}-distribution
    intervals for linear models. Falls back to Wald on profiling failure.
    Quasi-likelihood families always use Wald (no true likelihood).
  \item \code{"wald"} - Wald intervals (coefficient \eqn{\pm} \emph{z}
    \eqn{\times} SE) for all model types. Faster but less accurate near
    boundary conditions or with small subgroups.
}
Cox and mixed-effects models use Wald intervals regardless of this setting.
Set globally with \code{options(summata.conf_method = "wald")} to use Wald
throughout a session. Note: when \code{method = "screen"} and
\code{columns = "multi"}, the internal screening pass always uses Wald
since only \emph{p}-values are needed for variable selection.}

\item{parallel}{Logical. If \code{TRUE} (default), fits univariable models
in parallel using multiple CPU cores for improved performance.}

\item{n_cores}{Integer specifying the number of CPU cores to use for
parallel processing. Default is \code{NULL} (auto-detect: uses
\code{detectCores() - 1}). Ignored when \code{parallel = FALSE}.}

\item{number_format}{Character string or two-element character vector
  controlling thousand and decimal separators in formatted output. Named
  presets:
  \itemize{
    \item \code{"us"} - Comma thousands, period decimal: \code{1,234.56} [default]
    \item \code{"eu"} - Period thousands, comma decimal: \code{1.234,56}
    \item \code{"space"} - Thin-space thousands, period decimal: \code{1 234.56}
      (SI/ISO 31-0)
    \item \code{"none"} - No thousands separator: \code{1234.56}
  }
  Or provide a custom two-element vector \code{c(big.mark, decimal.mark)},
  \emph{e.g.}, \code{c("'", ".")} for Swiss-style: \verb{1'234.56}.

  When \code{NULL} (default), uses
  \code{getOption("summata.number_format", "us")}. Set the global option
  once per session to avoid passing this argument repeatedly:
  \preformatted{
    options(summata.number_format = "eu")
  }}

\item{verbose}{Logical. If \code{TRUE}, displays model fitting warnings
(\emph{e.g.,} singular fit, convergence issues). If \code{FALSE} (default),
routine fitting messages are suppressed while unexpected warnings are
preserved. When \code{NULL}, uses
\code{getOption("summata.verbose", FALSE)}.}

\item{...}{Additional arguments passed to model fitting functions (\emph{e.g.,} 
\code{weights}, \code{subset}, \code{na.action}).}
}
\value{
Depends on \code{return_type} parameter:
  
  When \code{return_type = "table"} (default): A data.table with S3 class 
  \code{"fullfit_result"} containing:
  \describe{
    \item{Variable}{Character. Predictor name or custom label}
    \item{Group}{Character. Category level for factors, empty for continuous}
    \item{n/n_group}{Integer. Sample sizes (if \code{show_n = TRUE}). For
      variables included in the multivariable model, reflects the
      complete-case sample size from the fitted model (listwise deletion
      across all included predictors). For variables not selected into the
      multivariable model, reflects the per-variable sample size from the
      univariable analysis. This follows STROBE guideline item 12,
      which recommends reporting the number of participants included at
      each stage of analysis.}
    \item{events/events_group}{Integer. Event counts (if \code{show_events = TRUE}).
      Same complete-case convention as \code{n}: multivariable rows show
      events from the fitted model, univariable-only rows show
      per-variable counts.}
    \item{OR/HR/RR/Coefficient (95\% CI)}{Character. Unadjusted effect 
      (if \code{columns} includes "uni" and \code{metrics} includes "effect")}
    \item{Uni p}{Character. Univariable \emph{p}-value (if \code{columns} includes 
      "uni" and \code{metrics} includes "p")}
    \item{aOR/aHR/aRR/Adj. Coefficient (95\% CI)}{Character. Adjusted effect 
      (if \code{columns} includes "multi" and \code{metrics} includes "effect")}
    \item{Multi p}{Character. Multivariable \emph{p}-value (if \code{columns} 
      includes "multi" and \code{metrics} includes "p")}
  }
  
  When \code{return_type = "model"}: The fitted multivariable model object 
  (glm, lm, coxph, \emph{etc.}).
  
  When \code{return_type = "both"}: A list with two elements:
  \describe{
    \item{table}{The formatted results data.table}
    \item{model}{The fitted multivariable model object}
  }
  
  The table includes the following attributes:
  \describe{
    \item{outcome}{Character. The outcome variable name}
    \item{model_type}{Character. The regression model type}
    \item{method}{Character. The variable selection method used}
    \item{columns}{Character. Which columns were displayed}
    \item{model}{The multivariable model object (if fitted)}
    \item{uni_results}{The complete univariable screening results}
    \item{n_multi}{Integer. Number of predictors in multivariable model}
    \item{screened}{Character vector. Names of predictors that passed 
      univariable screening at the specified \emph{p}-value threshold}
    \item{significant}{Character vector. Names of variables with p < 0.05
      in the multivariable model (or univariable if multivariable was not
      fitted)}
    \item{analysis_counts}{List. How much of the supplied data reached the
      models, with elements \code{n_supplied}, \code{n_analyzed},
      \code{n_missing_outcome} and \code{n_missing_predictor}, plus
      \code{events_supplied} and \code{events_analyzed} where the model
      type carries an event count. The screening models and the
      multivariable model rest on different samples whenever a predictor
      carries missing values, so \code{n_analyzed} holds one value per
      model and the reported sample may be a range. The \code{print()}
      method always reports the analyzed sample}
  }
}
\description{
Executes a comprehensive regression analysis pipeline that combines univariable 
screening, automatic/manual variable selection, and multivariable modeling 
in a single function call. This function is designed to streamline the complete 
analytical workflow from initial exploration to final adjusted models, with 
publication-ready formatted output showing both univariable and multivariable 
results side-by-side if desired.
}
\details{
\strong{Analysis Workflow:}

The function implements a complete regression analysis pipeline:
\enumerate{
  \item \strong{Univariable screening}: Fits separate models for each 
    predictor (outcome ~ predictor). Each predictor is tested independently 
    to understand crude associations.
  \item \strong{Variable selection}: Based on the \code{method} parameter:
    \itemize{
      \item \code{"screen"}: Automatically selects predictors with univariable 
        p \eqn{\le} \code{p_threshold}
      \item \code{"all"}: Includes all predictors (no selection)
      \item \code{"custom"}: Uses predictors specified in \code{multi_predictors}
    }
  \item \strong{Multivariable modeling}: Fits a single model with selected 
    predictors (outcome ~ predictor1 + predictor2 + ...). Estimates are 
    adjusted for all other variables in the model.
  \item \strong{Output formatting}: Combines results into publication-ready 
    table with appropriate effect measures and formatting.
}

\strong{Variable Selection Strategies:}

\emph{"Screen" Method} (\code{method = "screen"}):
\itemize{
  \item Uses \emph{p}-value threshold for automatic selection
  \item Liberal thresholds (\emph{e.g.,} 0.20) cast a wide net to avoid missing 
    important predictors
  \item Stricter thresholds (\emph{e.g.,} 0.05) focus on strongly associated predictors
  \item Helps reduce overfitting and multicollinearity
  \item Common in exploratory analyses and when sample size is limited
}

\emph{"All" Method} (\code{method = "all"}):
\itemize{
  \item No variable selection; includes all predictors
  \item Appropriate when all variables are theoretically important
  \item Risk of overfitting with many predictors relative to sample size
  \item Useful for confirmatory analyses with pre-specified models
}

\emph{"Custom" Method} (\code{method = "custom"}):
\itemize{
  \item Manual selection based on subject matter knowledge
  \item Runs univariable analysis for all predictors (for comparison)
  \item Includes only specified predictors in multivariable model
  \item Ideal for theory-driven model building
  \item Allows comparison of unadjusted vs adjusted effects for all variables
}

\strong{Interpreting Results:}

When \code{columns = "both"} (default), tables show:
\itemize{
  \item \strong{Univariable columns}: Crude associations, unadjusted for 
    other variables. Labeled as "OR/HR/RR/Coefficient (95\% CI)" and "Uni \emph{p}"
  \item \strong{Multivariable columns}: Adjusted associations, accounting 
    for all other predictors in the model. Labeled as "aOR/aHR/aRR/Adj. Coefficient 
    (95\% CI)" and "Multi \emph{p}" ("a" = adjusted)
  \item Variables not meeting selection criteria show "-" in multivariable columns
}

Comparing univariable and multivariable results helps identify:
\itemize{
  \item \strong{Confounding}: Large changes in effect estimates
  \item \strong{Independent effects}: Similar univariable and multivariable 
    estimates
  \item \strong{Mediation}: Attenuated effects in multivariable model
  \item \strong{Suppression}: Effects that emerge only after adjustment
}

\strong{Sample Size Considerations:}

Rule of thumb for multivariable models:
\itemize{
  \item \strong{Logistic regression}: \eqn{\ge} 10 events per predictor variable
  \item \strong{Cox regression}:  \eqn{\ge} 10 events per predictor variable
  \item \strong{Linear regression}: \eqn{\ge} 10-20 observations per predictor
}

Use screening methods to reduce predictor count when these ratios are not met.
}
\examples{
# Load example data
data(clintrial)
data(clintrial_labels)

# Example 1: Basic screening with p < 0.05 threshold
result1 <- fullfit(
    data = clintrial,
    outcome = "os_status",
    predictors = c("age", "sex", "bmi", "smoking",
                   "hypertension", "diabetes",
                   "treatment", "stage"),
    method = "screen",
    p_threshold = 0.05,
    labels = clintrial_labels
)
print(result1)

\donttest{

# Example 2: Include all predictors (no selection)
result2 <- fullfit(
    data = clintrial,
    outcome = "os_status",
    predictors = c("age", "sex", "treatment", "stage"),
    method = "all",
    labels = clintrial_labels
)
print(result2)

# Example 3: Custom variable selection
result3 <- fullfit(
    data = clintrial,
    outcome = "os_status",
    predictors = c("age", "sex", "bmi", "smoking", "treatment", "stage"),
    method = "custom",
    multi_predictors = c("age", "treatment", "stage"),
    labels = clintrial_labels
)
print(result3)

# Example 4: Cox regression with screening
library(survival)
cox_result <- fullfit(
    data = clintrial,
    outcome = "Surv(os_months, os_status)",
    predictors = c("age", "sex", "treatment", "stage"),
    model_type = "coxph",
    method = "screen",
    p_threshold = 0.10,
    labels = clintrial_labels
)
print(cox_result)

# Example 5: Linear regression without screening
linear_result <- fullfit(
    data = clintrial,
    outcome = "bmi",
    predictors = c("age", "sex", "smoking", "creatinine"),
    model_type = "lm",
    method = "all",
    labels = clintrial_labels
)
print(linear_result)

# Example 6: Poisson regression for count outcomes
poisson_result <- fullfit(
    data = clintrial,
    outcome = "fu_count",
    predictors = c("age", "stage", "treatment", "surgery"),
    model_type = "glm",
    family = "poisson",
    method = "all",
    labels = clintrial_labels
)
print(poisson_result)

# Example 7: Show only multivariable results
multi_only <- fullfit(
    data = clintrial,
    outcome = "os_status",
    predictors = c("age", "sex", "treatment", "stage"),
    method = "all",
    columns = "multi",
    labels = clintrial_labels
)
print(multi_only)

# Example 8: Return both table and model object
both <- fullfit(
    data = clintrial,
    outcome = "os_status",
    predictors = c("age", "sex", "treatment", "stage"),
    method = "all",
    return_type = "both",
    labels = clintrial_labels
)
print(both$table)
summary(both$model)

# Example 9: Keep univariable models for diagnostics
with_models <- fullfit(
    data = clintrial,
    outcome = "os_status",
    predictors = c("age", "bmi", "creatinine"),
    keep_models = TRUE
)
uni_results <- attr(with_models, "uni_results")
uni_models <- attr(uni_results, "models")
summary(uni_models[["age"]])

# Example 10: Linear mixed effects with site clustering
if (requireNamespace("lme4", quietly = TRUE)) {
    lmer_result <- fullfit(
        data = clintrial,
        outcome = "los_days",
        predictors = c("age", "treatment", "surgery", "stage"),
        random = "(1|site)",
        model_type = "lmer",
        method = "all",
        labels = clintrial_labels
    )
    print(lmer_result)
}

}

}
\seealso{
\code{\link{uniscreen}} for univariable screening only,
\code{\link{fit}} for fitting a single multivariable model,
\code{\link{compfit}} for comparing multiple models,
\code{\link{desctable}} for descriptive statistics,
\code{\link{autoforest}} for forest plots of the multivariable models,
\code{\link{forestsave}} for exporting forest plots,
\code{\link{tablesave}} for exporting tables

Other regression functions:
\code{\link[=compfit]{compfit()}},
\code{\link[=fit]{fit()}},
\code{\link[=multifit]{multifit()}},
\code{\link[=print.compfit_result]{print.compfit_result()}},
\code{\link[=print.fit_result]{print.fit_result()}},
\code{\link[=print.fullfit_result]{print.fullfit_result()}},
\code{\link[=print.multifit_result]{print.multifit_result()}},
\code{\link[=print.uniscreen_result]{print.uniscreen_result()}},
\code{\link[=uniscreen]{uniscreen()}}
}
\concept{regression functions}
