gfoRmula: An R package for estimating effects of general time-varying treatment interventions via the parametric g-formula

Victoria Lin, Sean McGrath, Zilu Zhang, Lucia C. Petito, Roger Logan, Miguel A. Hernán, Jessica G. Young

Abstract

Researchers are often interested in using longitudinal data to estimate the causal effects of hypothetical time-varying treatment interventions on the mean or risk of a future outcome. Standard regression/conditioning methods for confounding control generally fail to recover causal effects when time-varying confounders are themselves affected by past treatment. In such settings, estimators derived from Robins's g-formula may recover time-varying treatment effects provided sufficient covariates are measured to control confounding by unmeasured risk factors. The package gfoRmula implements in R one such estimator: the parametric g-formula. This estimator easily adapts to binary or continuous time-varying treatments as well as contrasts defined by static or dynamic, deterministic or random treatment interventions, as well as interventions that depend on the natural value of treatment. The package accommodates survival outcomes as well as binary or continuous end of follow-up outcomes. For survival outcomes, the package has different options for handling competing events. This paper describes the gfoRmula package, along with motivating background, features, and examples.

Introduction

In longitudinal studies, researchers frequently encounter complex relationships between treatments and covariates that evolve over time. A significant challenge in these settings is the presence of time-varying confounding. This occurs when a variable acts as both a confounder (influencing future treatment assignment) and a consequence of prior treatment.

A classic example is found in HIV research: a patient’s CD4 cell count (an immune system marker) influences the clinical decision to initiate antiretroviral therapy. However, the therapy itself subsequently alters the CD4 count. This creates a feedback loop that standard regression or conditioning methods cannot resolve. Standard methods that adjust for time-varying CD4 counts would inadvertently block the causal path from past treatment to the outcome through CD4 count, leading to biased estimates. The gfoRmula package addresses this by implementing Robins’s parametric g-formula, a robust method designed to untangle these dependencies and estimate the effects of hypothetical intervention strategies.

Methodology: The Parametric G-Formula

The gfoRmula package utilizes the parametric g-formula (also known as g-computation) to estimate causal effects. The core logic involves creating a "digital twin" of the study population through a structured three-step simulation algorithm:

  1. Estimation Phase: Using the observed longitudinal data, the software fits parametric models—typically generalized linear models (GLMs)—to estimate the conditional distributions of all time-varying covariates and the outcome at each discrete time point.
  2. Simulation Phase: The package employs Monte Carlo simulation to generate a large hypothetical population. In this simulated environment, the "treatment" is assigned according to a user-specified intervention rule. These rules can be static (e.g., "always treat") or dynamic (e.g., "initiate treatment only if a biomarker falls below a certain threshold"). Other variables in the simulation evolve according to the conditional distributions estimated in the first phase.
  3. Comparison Phase: Finally, the package calculates the risk or mean of the outcome within the simulated population. By comparing results across different intervention rules, researchers can derive causal contrasts such as risk ratios or risk differences.

A key strength of gfoRmula is its extensibility. While it provides robust defaults, users can integrate custom R functions for model fitting (e.g., incorporating machine learning techniques like Random Forests) and define highly specific treatment histories.

Package Features and Built-in Datasets

The package is designed to be versatile, supporting various outcome types and complex data structures. It includes four primary example datasets to demonstrate its capabilities:

  • basicdata_nocomp: A survival dataset without competing risks, ideal for testing basic static treatment strategies.
  • basicdata: A survival dataset that includes competing events (e.g., mortality from unrelated causes), allowing researchers to distinguish between "total effects" and "controlled direct effects."
  • binary_eofdata: Designed for binary outcomes measured at a single point at the end of follow-up (EOF).
  • continuous_eofdata: Designed for continuous outcomes measured at the end of follow-up.

These datasets typically represent longitudinal cohorts of approximately 2,500 individuals followed over multiple time points, providing a realistic testing ground for causal inference workflows.

Advanced Capabilities

Beyond simple treatment comparisons, gfoRmula offers several advanced features:

  • Dynamic Interventions: The package excels at evaluating "what-if" scenarios that depend on a patient's evolving health status. This allows for the testing of personalized medicine strategies.
  • Handling Competing Risks: In survival analysis, competing risks can prevent the primary event of interest from occurring. gfoRmula provides flexible options to treat these as either censoring events or as part of the total causal effect calculation.
  • Incorporating Deterministic Knowledge: Researchers can hard-code known biological or logical constraints into the simulation. For instance, if a patient is recorded as having reached a terminal state or a specific biological milestone at time $k$, the simulation can be constrained to prevent impossible transitions at time $k+1$. This improves the precision and biological plausibility of the results.
  • Computational Efficiency: Given that Monte Carlo simulations and bootstrapping (used for calculating confidence intervals) are resource-intensive, the package includes built-in parallelization to distribute the workload across multiple CPU cores.

Results and Validation

The authors demonstrate that gfoRmula successfully recovers expected causal estimates across various scenarios. In survival analysis examples, the package generates "g-form risks" for different strategies (e.g., comparing a risk of 0.731 under "Never Treat" to 0.234 under "Always Treat"), automatically providing the Risk Ratio and Risk Difference.

Furthermore, the package includes S3 plot methods that allow for visual validation. These methods compare the parametric g-formula estimates against non-parametric estimates (such as Kaplan-Meier curves) for the "natural course" (the observed data). Close alignment between these curves suggests that the parametric models are well-specified, increasing confidence in the resulting causal inferences.

Limitations and Future Directions

While powerful, the parametric g-formula relies on two critical assumptions:

  1. Model Specification: The accuracy of the results depends on the correctness of the underlying parametric models. If the GLMs used to simulate covariates are misspecified, the final causal estimates will be biased.
  2. No Unmeasured Confounding: Like most causal inference methods, it assumes that all variables influencing both treatment and the outcome have been measured and included in the models.

Additionally, despite parallelization, large-scale simulations with many bootstrap samples remain computationally demanding. Future developments may involve integrating automated machine learning (such as Double Machine Learning) to alleviate the burden of manual model specification and improve robustness against misspecification.

Summary updated

Abstract

Researchers are often interested in using longitudinal data to estimate the causal effects of hypothetical time-varying treatment interventions on the mean or risk of a future outcome. Standard regression/conditioning methods for confounding control generally fail to recover causal effects when time-varying confounders are themselves affected by past treatment. In such settings, estimators derived from Robins's g-formula may recover time-varying treatment effects provided sufficient covariates are measured to control confounding by unmeasured risk factors. The package gfoRmula implements in R one such estimator: the parametric g-formula. This estimator easily adapts to binary or continuous time-varying treatments as well as contrasts defined by static or dynamic, deterministic or random treatment interventions, as well as interventions that depend on the natural value of treatment. The package accommodates survival outcomes as well as binary or continuous end of follow-up outcomes. For survival outcomes, the package has different options for handling competing events. This paper describes the gfoRmula package, along with motivating background, features, and examples.
BibTeX
@article{lin2020gformula,
  author = {Victoria Lin and Sean McGrath and Zilu Zhang and Lucia C. Petito and Roger Logan and Miguel A. Hernán and Jessica G. Young},
  title = {{gfoRmula: An R package for estimating effects of general time-varying treatment interventions via the parametric g-formula}},
  journal = {Patterns},
  year = {2020},
  doi = {10.1016/j.patter.2020.100008},
}
Figure