---
title: "Marginal standardization"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Marginal standardization}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```


# The basics

Marginal standardization, `approach = "margstd_delta"` and `approach = "margstd_boot"`, makes use of the good convergence properties of the logit link, which is also guaranteed to result in probabilities within (0; 1). 

After fitting a logistic model, predicted probabilities for each observation are obtained for the levels of the exposure variable. Risk ratios and risk differences are calculated by contrasting the predicted probabilities as ratios or differences. Standard errors and confidence intervals are obtained via the delta method or via bootstrapping the entire procedure. 

We use the same example data as in the [Get Started vignette](risks.html#an-example-cohort-study).

```{r load, message = FALSE}
library(risks)  # provides riskratio(), riskdiff(), postestimation functions
library(dplyr)  # For data handling
library(broom)  # For tidy() model summaries
data(breastcancer)
```

We fit the same risk difference model as in the [Get Started vignette](risks.html#adjusted-risk-differences), this time explicitly specifying `approach = "margstd_delta"`:

```{r margstd}
fit_margstd <- riskdiff(formula = death ~ stage + receptor, 
                        data = breastcancer, 
                        approach = "margstd_delta")
summary(fit_margstd)
```

Consistent with earlier results, we observed that women with stage III breast cancer have a 57 percentage points higher risk of death, adjusting for hormone receptor status.

Note that coefficients and standard errors are only estimated for the exposure variable. Model fit characteristics and predicted values stem directly from the underlying logistic model.


# Choice of exposure variable

Standardization can only be done over one exposure variable, and thus no coefficients are estimated for other variables in the model.

* By default, the first right-hand variable in the model formula will be assumed to be the exposure. The variable types `logical`, `factor`, `ordered`, and `character` are taken to represent categorical variables.
* Using `variable =`, a different variable can be specified.
* Using `at =`, levels for contrasts and the order of levels can be specified. The first level is used as the reference with a risk ratio of 1 or a risk difference of 0. A warning will be shown for continuous values if the requested levels exceed the range of data (extrapolation).


Requesting estimates for a different exposure variable, using `variable = "receptor"`:

```{r margstd2}
fit_margstd2 <- riskdiff(formula = death ~ stage + receptor, 
                         data = breastcancer, 
                         approach = "margstd_delta", variable = "receptor")
summary(fit_margstd2)
```


# Bootstrap confidence intervals

Marginal standardization cannot rely on analytical standard error formulae. One approach (`"margstd_delta"`) is the delta method. Alternatively, parametric bootstrapping (`"margstd_boot"` with the default, `bootci = "bca"`) can be used: given the initial maximum-likelihood estimates of the coefficients and the observed predictors, the outcome vector is predicted from a binomial distribution. The model is fit again using the predicted outcomes and observed predictors. Repeating this process generates the empirical distribution of the coefficients. 

Confidence intervals for coefficients are calculated based on BC~a~ confidence intervals for parametric bootstrapping (Efron B, Narasimhan B. The Automatic Construction of Bootstrap Confidence Intervals. [J Comput Graph Stat 2020;29(3):608-619](https://pubmed.ncbi.nlm.nih.gov/33727780/)).

For comparison purposes, alternative approaches to bootstrapping and confidence interval estimation can requested in `tidy()`, `summary.margstd()`, and `confint()`:

* `bootci = "normal"`: Normality-based confidence intervals after parametric bootstrapping. These may give out-of-range estimates for confidence limits.
* `bootci = "nonpar"`: BC~a~ intervals after *nonparametric* bootstrapping. Here, the data are resampled, rather than the outcome predicted from the model. Especially in the small datasets in which regular binomial models with log links may not converge and marginal standardization may be the only option, resampling the data comes with the risk of empty strata in the resamples, resulting in sparse-data bias or model nonconvergence. The resulting confidence intervals may be too narrow. This option should be used with caution.

When using `tidy()` to access model results, the parameter `bootverbose = TRUE` will add bootstrapping parameters and properties to the tibble:

```{r margstd_bootverbose}
fit_margstd3 <- riskdiff(formula = death ~ stage + receptor, 
                         data = breastcancer, 
                         approach = "margstd_boot")
summary(fit_margstd3)

tidy(fit_margstd3, bootverbose = TRUE) %>%
  select(-statistic, -p.value)  # allow the other columns to get printed instead
```

* `bootrepeats`: Number of bootstrap repeats.
* `bootci`: Type of bootstrap confidence interval (`bca`, `normal`, or `nonpar`, see above).
* `jacksd.low` and `jacksd.high`: Jackknife-based Monte-Carlo standard errors for the lower and upper limits of the confidence interval. Available for `bca` intervals only. If these simulation errors are large compared to the desired precision of the confidence limits, then the number of bootstrap repeats needs to be substantially increased.


# Bootstrap repeats

The default are (currently) only 1000 bootstrap repeats to reduce initial computation time. If the calculation of BC~a~ confidence intervals fails with an error, and for final, precise estimates, the number of repeats should be increased to >>1000. Use the option `bootrepeats =` in `summary()`, `tidy()`, or `confint()`. 

For reproducibility, a seed should be set (e.g., `set.seed(123)`).
