---
title: "Covariate Adjustment in Randomized Controlled Trials"
author: "Se Yoon Lee"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Covariate Adjustment in Randomized Controlled Trials}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 4.5,
  fig.align = "center"
)
```

```{r load-package}
library(RCTCovAdj)
```

## Aim and statistical setting

Baseline covariates can improve precision in a randomized controlled trial
(RCT) when they predict the outcome. Adjustment is most useful when its target,
estimator, and variance calculation are defined together. `RCTCovAdj` implements
the continuous-outcome procedures studied in the accompanying paper and makes
these choices explicit.

For each participant, let $O=(X,A,Y)$ denote the observed data, where $X$
contains covariates measured before treatment, $A\in\{0,1\}$ is the randomized
assignment, and $Y$ is the observed outcome. The
main analysis assumes independent sampling from a target population and
Bernoulli assignment with known probability

\[
  \Pr(A=1\mid X)=\pi, \qquad 0<\pi<1.
\]

Here $Y(a)$ is the potential outcome under assignment $a$, assignment $A$ is
independent of $(X,Y(0),Y(1))$, and consistency gives
$Y=AY(1)+(1-A)Y(0)$. Both potential outcomes have finite second moments.

The treatment-specific conditional means are
$m_a(x)=E(Y\mid A=a,X=x)$. The target is the marginal mean difference

\[
  \psi=E\{m_1(X)-m_0(X)\}=E\{Y(1)-Y(0)\}.
\]

Randomization identifies this effect without a model for $m_0$ or $m_1$.
Covariate adjustment changes how precisely the effect is estimated; it does not
change the marginal target when both treatment-specific means are averaged over
the same covariate distribution.

The main theory also assumes that the outcome and every baseline variable used
for adjustment are observed for every participant. Missing outcomes require
assumptions that identify the intended estimand and an analysis aligned with the
outcome-observation process. Covariate-adaptive or fixed-count randomization,
other dependent assignment schemes, and finite-population targets require
design- and target-specific repeated-sampling arguments. Simply adding
covariates to a regression does not supply these arguments.

## Where the precision gain comes from

Under known Bernoulli randomization, the efficient influence function for the
marginal mean difference is

\[
D^*(O)=m_1(X)-m_0(X)-\psi
  +\frac{A}{\pi}\{Y-m_1(X)\}
  -\frac{1-A}{1-\pi}\{Y-m_0(X)\}.
\]

The baseline signal that can be removed from the unadjusted estimator is
governed by

\[
  q^*(x)=(1-\pi)m_1(x)+\pi m_0(x).
\]

The conditional mean in the less frequently assigned arm receives greater
weight. This opposite-arm weighting matters under unequal allocation. It also
shows why strong prediction within each arm does not by itself guarantee a
precision gain: the two arm-specific signals can cancel in $q^*$.

For any fixed square-integrable working function $q$, the augmented
estimating function

\[
\varphi_q(O)=\frac{AY}{\pi}-\frac{(1-A)Y}{1-\pi}
  -\frac{A-\pi}{\pi(1-\pi)}q(X)
\]

has mean $\psi$. Its first-order variance exceeds the efficiency bound by

\[
  \frac{E[\{q(X)-q^*(X)\}^2]}{\pi(1-\pi)}.
\]

The ratio difference in means corresponds at first order to the constant
$q_U=E\{q^*(X)\}$, whereas $q=0$ gives a fixed-denominator contrast. It follows
that the gain from the ratio difference in means to the efficient estimator is
$\operatorname{Var}\{q^*(X)\}/[\pi(1-\pi)]$.

Thus approximation quality has a direct variance interpretation. A poor
working adjustment can lose precision. With honest cross-fitting, a fixed
number of folds whose proportions remain bounded away from zero, and the stated
moment conditions, an estimator whose learned adjustment converges in
population mean square to the deterministic function $q^*$ attains the
semiparametric bound.

## Four analysis strategies

`rct_adjust()` reports three fixed-dimensional procedures. Supplying the known
design probability through `allocation` keeps the analysis aligned with the
randomization law.

* **Unadjusted difference in means (DIM).** The estimate is the observed treatment-arm
  mean minus the observed control-arm mean. Ratio normalization uses the
  realized arm sizes, although its first-order analysis depends on the design
  probability.
* **Common-slope analysis of covariance (ANCOVA).** A pooled regression uses a
  single covariate slope. Under balanced allocation it has the same first-order
  slope weighting as interacted linear adjustment. Under unequal allocation
  and different arm-specific slopes, it can be less precise than the
  unadjusted estimator.
* **Interacted standardization.** Separate regressions are fit in the two arms,
  and their fitted contrast is averaged over all observed baseline covariates.
  This estimates the variance-minimizing adjustment within the chosen linear
  feature span. Its influence-function standard error includes variation from
  sampling the covariate distribution used for standardization.
* **Cross-fitted adjustment.** `rct_crossfit()` trains predictions outside each
  evaluation fold and averages one held-out estimating contribution per
  participant. With known allocation, mean-square convergence of the weighted
  prediction to a deterministic limit suffices for the first-order expansion;
  no propensity-score model is needed.

The term *linear* refers to a feature span, rather than an assertion that the
true conditional means are linear. Predetermined transformations such as
squares or splines can be supplied as columns of the covariate matrix.

## A small simulated RCT

The following example has a continuous outcome, balanced assignment, and
treatment-specific slopes. The code is intentionally small enough to run while
the vignette is built.

```{r small-trial}
set.seed(20260904)
n <- 600L
x <- rnorm(n)
a <- rbinom(n, size = 1L, prob = 0.5)
y <- 0.5 * a + (2 - 3 * a) * x + rnorm(n)

trial <- data.frame(outcome = y, treatment = a, x = x)
head(trial)
```

The estimand is the marginal treatment mean difference, which equals $0.5$
under this data-generating law. The adjusted analyses use the same covariate and
the same marginal target.

```{r fixed-adjustment}
fit <- rct_adjust(
  outcome = trial$outcome,
  treatment = trial$treatment,
  covariates = trial["x"],
  allocation = 0.5,
  methods = c("unadjusted", "ancova", "interacted")
)
fit
```

The columns labeled `estimate`, `std.error`, and `conf.low`--`conf.high` give
the point estimate, its standard error, and a normal-reference confidence
interval. Sampling variation may make one method look better in a single
dataset. Precision comparisons concern repeated-sampling variances, not the
distance of one realized estimate from the known simulation truth.

The cross-fitted linear procedure uses held-out predictions. Fold construction
is deterministic once the seed is fixed; each fitted regression excludes the
observations on which its estimating contributions are evaluated.

```{r crossfit-adjustment}
fit_cf <- rct_crossfit(
  outcome = trial$outcome,
  treatment = trial$treatment,
  covariates = trial["x"],
  allocation = 0.5,
  learner = "linear",
  folds = 2L,
  seed = 2718L
)
fit_cf
```

The built-in quadratic learner adds the square of each model-matrix column; it
does not add pairwise interactions or spline bases. Other nonlinear structures
can be supplied as prespecified engineered columns or through a custom learner.

```{r quadratic-crossfit}
nonlinear_trial <- simulate_rct_case("A", n = 600L, seed = 314L)
rct_crossfit(
  outcome = nonlinear_trial$outcome,
  treatment = nonlinear_trial$treatment,
  covariates = nonlinear_trial["x"],
  allocation = 0.5,
  learner = "quadratic",
  folds = 2L,
  seed = 2718L
)
```

## Standard errors after empirical standardization

An interacted regression coefficient and an empirically standardized contrast
are different statistical objects. When arm-specific slopes differ, averaging
the fitted contrast over the sampled covariates contributes first-order
variation for the fixed superpopulation target. The default interacted result
from `rct_adjust()` uses the joint influence-function variance that includes
this component.

Setting `diagnostic_hc2 = TRUE` additionally reports the coefficient-only
heteroskedasticity-consistent type 2 (HC2) calculation used as a diagnostic in
the paper.

```{r hc2-diagnostic}
rct_adjust(
  outcome = trial$outcome,
  treatment = trial$treatment,
  covariates = trial["x"],
  allocation = 0.5,
  methods = "interacted",
  diagnostic_hc2 = TRUE
)
```

HC2 changes residual weights to account for leverage. It does not restore the
variation omitted by treating the empirical standardization distribution as
fixed. Consequently, coefficient-only HC2 inference is not the package default
for the superpopulation target.

## Application 1: postoperative throat-pain scores

The paper applies these methods to 30-minute postoperative throat-pain scores
from a licorice-gargle RCT. `RCTCovAdj` distributes neither the trial records
nor results derived from them. The source portal states that permission from
the data contributor or corresponding author is required before the records
are used in a new publication. Installing the package grants no right to
analyze, publish, or redistribute the records or derived output.

After obtaining the required permission and an authorized copy of the reviewed
RDA file, a user can verify and analyze it locally. `read_licorice_data()` checks
both the expected file fingerprint and the required structure before returning
the analysis data. This code is not run during package checks because the input
is not part of the package.

```{r licorice-authorized, eval=FALSE}
licorice <- read_licorice_data(file.choose())
licorice_fit <- analyze_licorice(licorice)
licorice_fit$estimates
plot_licorice_results(licorice_fit)
```

The optional `medicaldata` package supplies the source-format data through a
separate distribution. Its availability does not establish permission for a
proposed use. A user whose permission covers that copy may prepare it as
follows:

```{r licorice-medicaldata, eval=FALSE}
licorice <- prepare_licorice_data()
licorice_fit <- analyze_licorice(licorice)
```

Calling `prepare_licorice_data()` does not itself grant permission to analyze,
publish, or redistribute the participant records or derived output. In either
route, `analyze_licorice()` returns the estimates, outcome and baseline
summaries, bounded-score completion analysis, numerical diagnostics, and
working-model coefficients needed to reproduce the paper's application.

## Application 2: power and sample size

For a regular, consistently studentized analysis with influence-function
variance factor $V$, the magnitude of the normal-approximation noncentrality
parameter at total sample size $n$ and planning effect $\Delta$ is
$\sqrt{n}|\Delta|/\sqrt{V}$. Holding the effect, allocation, type I error,
test alternative, and target power fixed therefore gives

\[
  \frac{n_j}{n_k}=\frac{V_j}{V_k}
\]

before integer rounding and attrition inflation.

The package evaluates one- and two-sided power under the normal approximation
and numerically inverts it. The following values reproduce the balanced
nonlinear planning law (Case A) used in the paper.

```{r sample-size-example}
variance <- c(
  unadjusted = 12.5,
  interacted_linear = 8.5,
  efficient_quadratic = 4.0
)

rct_sample_size(
  effect = 0.5,
  variance = variance,
  power = 0.80,
  alpha = 0.05,
  alternative = "two.sided"
)
```

The corresponding rounded totals are 393, 267, and 126. The variance factor of
pooled ANCOVA can exceed the unadjusted factor under unequal allocation. The
second planning law (Case C) makes this visible.

```{r power-design, fig.alt="Two-panel normal-approximation power curves under balanced nonlinear Case A and unequal-allocation Case C, comparing unadjusted, interacted, and efficient quadratic or pooled ANCOVA analyses; symbols mark 80 percent power.", fig.cap="Normal-approximation power under planning Cases A and C. Symbols mark the smallest integer total sample sizes attaining 80% power for each analysis."}
design <- paper_power_design()
design$sample_sizes
plot_power_design(design)
```

These calculations are design consequences of specified planning laws. The
semiparametric bound is an optimistic planning variance unless the proposed
estimator can learn the relevant prognostic signal at the intended sample size.
Use credible external information or prespecified sensitivity scenarios for
the variance factors, and assess the complete analysis under the actual
assignment scheme.

## Practical analysis checklist

Before using a covariate-adjusted analysis, specify:

1. the outcome, follow-up time, treatment contrast, and population over which
   the contrast is averaged;
2. the randomization probability and assignment scheme;
3. baseline variables and feature transformations;
4. whether treatment-specific regressions and empirical standardization are
   used;
5. the complete fold, training, tuning, and fallback rules for cross-fitting;
6. a variance estimator matched to the target and sampling experiment; and
7. a separate strategy for missing outcomes or intercurrent events.

The companion vignette, *Reproducing the Paper's Numerical Results*, documents
the simulation archive, deterministic study-design calculations, and the route
for rebuilding each numerical result.
