---
title: "Start Here: Model to Manuscript"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Start Here: Model to Manuscript}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, echo=FALSE, out.width='160px'}
logo_candidates <- c(
  "man/figures/gtregression_hex.png",
  "../man/figures/gtregression_hex.png"
)
logo_path <- logo_candidates[file.exists(logo_candidates)][1]

if (!is.na(logo_path)) {
  knitr::include_graphics(logo_path)
}
```

# gtregression

**Publication-ready regression tables and plots for real-world health data.**

`gtregression` helps you fit, adjust, stratify, visualise, and export
regression results with approachable R syntax. It supports logistic,
log-binomial, Poisson, robust Poisson, negative binomial, Cox survival,
parametric survival, and linear regression. `flextable` is the default table
engine, so outputs are Word-friendly from the start; `format = gt` remains
available for HTML-first workflows.

## What You Can Make

- Clean descriptive tables.
- Univariable and multivariable regression tables.
- Adjusted models with clear footnotes.
- Stratified regression outputs.
- Kaplan-Meier curves, survival summaries, Cox models, and parametric survival
  models.
- Forest plots and publication-style forest tables.
- Model diagnostics, model selection, confounding, and interaction checks.
- HTML, PDF, PNG, and Word outputs.

## What Powers the Package

`gtregression` is a readable interface over standard R modelling and reporting
packages. The fitted models remain available inside the returned objects, so
users can inspect the analysis behind the displayed table.

| Area | Core packages used |
|------------------------------------|------------------------------------|
| Data handling | `dplyr`, `purrr`, `tibble`, `rlang` |
| Regression and survival models | `stats`, `MASS`, `survival`, `risks`, `logistf` |
| Robust inference and model tidying | `sandwich`, `lmtest`, `broom`, `broom.helpers` |
| Tables and Word output | `flextable`, `officer`, `gt` |
| Plots and forest plots | `ggplot2`, `patchwork`, `forestploter`, `scales` |

## Install

```r
install.packages("gtregression")

# Development version
devtools::install_github("ThinkDenominator/gtregression")
```

## Prepare Example Data

The articles use `data_birthwt`, a small built-in dataset that is easy to
learn with.

```{r setup-birthwt, message=FALSE, warning=FALSE}
library(gtregression)
library(dplyr)

data("data_birthwt", package = "gtregression")

birthwt_data <- data_birthwt |>
  mutate(
    race = factor(race, levels = c(1, 2, 3),
                  labels = c("White", "Black", "Other")),
    smoke = factor(smoke, levels = c(0, 1), labels = c("No", "Yes")),
    ht = factor(ht, levels = c(0, 1), labels = c("No", "Yes")),
    ui = factor(ui, levels = c(0, 1), labels = c("No", "Yes")),
    low = factor(low, levels = c(0, 1), labels = c("Normal BW", "Low BW")),
    ptl_cat = ifelse(ptl > 0, "Yes", "No"),
    ftv_cat = case_when(
      ftv == 0 ~ "None",
      ftv == 1 ~ "One",
      ftv >= 2 ~ "Two or more"
    )
  ) |>
  mutate(
    ptl_cat = factor(ptl_cat, levels = c("No", "Yes")),
    ftv_cat = factor(ftv_cat, levels = c("None", "One", "Two or more"))
  )

birthwt_exposures <- c(
  "age", "lwt", "race", "smoke", "ht", "ui", "ptl_cat", "ftv_cat"
)

attr(birthwt_data$age, "label") <- "Maternal age"
attr(birthwt_data$lwt, "label") <- "Maternal weight"
attr(birthwt_data$race, "label") <- "Maternal race"
attr(birthwt_data$smoke, "label") <- "Smoking during pregnancy"
attr(birthwt_data$ht, "label") <- "Hypertension"
attr(birthwt_data$ui, "label") <- "Uterine irritability"
attr(birthwt_data$ptl_cat, "label") <- "Previous preterm labour"
attr(birthwt_data$ftv_cat, "label") <- "First trimester visits"
```

## Five-Minute Workflow

### Describe

```{r quick-describe, message=FALSE, warning=FALSE}
birthwt_summary <- descriptive_table(
  data = birthwt_data,
  exposures = birthwt_exposures,
  by = low,
  percent = column,
  show_overall = last,
  theme = clinical
)

birthwt_summary$table
```

### Model

```{r quick-model, message=FALSE, warning=FALSE}
birthwt_uni <- uni_reg(
  data = birthwt_data,
  outcome = low,
  exposures = birthwt_exposures,
  approach = logit,
  theme = clinical
)

birthwt_multi <- multi_reg(
  data = birthwt_data,
  outcome = low,
  exposures = c("smoke", "ht", "ui", "ptl_cat", "ftv_cat"),
  adjust_for = c("age", "lwt", "race"),
  approach = logit,
  theme = striped
)

birthwt_multi$table
```

### Visualise

```{r quick-plot, fig.width=12, fig.height=8,message=FALSE, warning=FALSE}
plot_reg(
  birthwt_multi,
  title = "Adjusted Regression for Low Birth Weight"
)

forest_reg(forest_df(birthwt_uni, birthwt_multi))
```

### Merge and Polish

```{r quick-merge, message=FALSE, warning=FALSE}
birthwt_final <- merge_tables(
  birthwt_summary,
  birthwt_uni,
  birthwt_multi,
  spanners = c("Clinical profile", "Crude OR", "Adjusted OR")
)

birthwt_final <- modify_table(
  birthwt_final,
  caption = "Clinical profile and regression estimates for low birth weight",
  caveat = "Adjusted estimates are adjusted for maternal age, maternal weight, and maternal race."
)

birthwt_final$table
```

Save helpers return file paths and use `tempdir()` when no directory is supplied,
which keeps examples CRAN-safe.

```{r quick-save, eval=FALSE}
save_table(birthwt_final, filename = "birthwt-table", format = html)
save_docx(tables = birthwt_final, filename = "birthwt-report")
```

## Where To Go Next

- [**Descriptive Tables**](descriptive-tables.html): build baseline tables users
  can read.
- [**Regression Tables**](regression-tables.html): create crude and adjusted
  publication-ready outputs.
- [**Survival Analysis**](survival-analysis.html): Kaplan-Meier curves, survival
  summaries, Cox regression, parametric survival models, and survival
  predictions.
- [**Causal Mediation**](causal-mediation.html): estimate direct, indirect,
  total, and proportion mediated effects with clear causal caveats.
- [**Visualise Results**](visualise-results.html): plot regression estimates and
  forest tables.
- [**Stratified Analysis**](stratified-analysis.html): repeat models across
  subgroups.
- [**Diagnostics**](diagnostics-selection.html): check convergence,
  collinearity, and model selection.
- [**Confounding & Interaction**](confounding-interaction.html): support
  interpretation and model decisions.
- [**Customize & Export**](customize-export.html): polish and save tables,
  plots, and reports.
