swaruplab/operon/clinical-biostatistics-logistic-regression

Claude Code and agent skill by swaruplab/operon

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Performs logistic regression for clinical trial outcomes (binary, ordinal, multinomial) with marginal-vs-conditional estimand reporting per FDA 2023 covariate adjustment guidance, g-computation/standardisation for marginal effects, modified Poisson for RR, Brant test for proportional odds, Firth penalty for separation, and Hauck-Donner detection. Use when modeling binary or ordinal endpoints in confirmatory or exploratory clinical trials.

Install

npx vskill@latest install swaruplab/operon/clinical-biostatistics-logistic-regression

SKILL.md

The same SKILL.md was published earlier as swaruplab/operon/clinical-biostatistics-logistic-regression.

Version Compatibility

Reference examples tested with: statsmodels 0.14+, scipy 1.12+, numpy 1.26+, pandas 2.1+, firthmodels 0.3+, marginaleffects 0.0.13+ (Python) / 0.20+ (R). R packages cited: RobinCar, marginaleffects, brant, MASS, VGAM.

Before using code patterns, verify installed versions match. If versions differ:

  • Python: pip show <package> then help(module.function) to check signatures
  • R: packageVersion('<pkg>') then ?function_name

If code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example to match the actual API rather than retrying.

Logistic Regression for Clinical Outcomes

"Model clinical outcomes with logistic regression" -> Estimate the marginal or conditional treatment effect on a binary or ordinal endpoint using a model that respects randomisation stratification, declares its estimand, and survives covariate misspecification.

Conditional vs marginal (the non-collapsibility subtlety): the OR is non-collapsible. The conditional OR from logistic regression is a different parameter than the marginal OR, even when there is NO confounding and randomisation is perfect. This is mathematical, not statistical bias. FDA 2023 favours marginal RD (via g-computation) for primary reporting to avoid parameter ambiguity. See clinical-biostatistics/effect-measures and Permutt 2020.

Algorithmic Taxonomy

ApproachEstimandInferenceStrengthFails when
Unadjusted logistic / chi-squareMarginal ORWald or LRSimple; transparentLoses efficiency vs adjusted (Senn 2013); inflates SE under stratified randomisation (Kahan-Morris 2012)
Logistic with covariates (ML, Wald CI)Conditional log-ORWaldStandard; widely availableConditional OR != marginal OR due to non-collapsibility (Permutt 2020); not the FDA 2023 primary estimand
Logistic + g-computation / standardisationMarginal RD/RR/ORInfluence function or bootstrap SEFDA 2023 recommended primary estimand for binaryRequires correct outcome model AND post-fit standardisation; needs robust SE machinery
Targeted Maximum Likelihood (TMLE)Marginal RD/RR/ORInfluence functionProvably efficient; doubly robust in observationalImplementation heavier; mostly R (tmle, tmle3); rare in confirmatory submissions
Modified Poisson with sandwich SEMarginal RRHC1/HC3 sandwichDirect RR estimation when prevalence >10%Slightly less efficient than log-binomial when log-binomial converges
Log-binomial regressionMarginal RRWaldDirect RR estimationFrequent convergence failure when predicted risk near 1
Firth penalised logisticConditional OR (penalised)Penalised LR test preferredHandles separation, rare events (<5% prevalence)Wald CI/p liberal; must use PLR test (Heinze-Schemper 2002)
Ordinal logistic (proportional odds)Common conditional OR across cut-pointsWald or LRPreserves ordering informationProportional odds assumption violation (Brant test)
Partial proportional oddsPO holds for some covariates, not othersHybridSalvages ordinal model when PO fails for one predictorIncreased complexity; harder interpretation
Multinomial logisticPer-category log-ORWaldNo PO assumption neededLoses efficiency; harder communication

Postdoc reading list: Permutt 2020 Stat Biopharm Res 12:45 (conditional vs marginal estimand); FDA May 2023 Final Guidance "Adjusting for Covariates in RCTs" (the regulatory rulebook); Tsiatis et al 2008 Stat Med 27:4658 (robust ANCOVA framework); Senn 2013 Stat Med 32:1439 (precision from adjustment even under perfect balance); Kahan-Morris 2012 Stat Med 31:328 (must adjust for stratification factors).

Decision Tree by Scenario

ScenarioRecommended approachWhy
RCT, binary primary endpoint, no covariate adjustment in SAPUnadjusted logistic with marginal OR; chi-square supportiveSimple regulatory case; consider whether covariate adjustment would gain power (Senn 2013)
RCT, binary primary, covariates pre-specified, FDA 2023 compliantLogistic adjusted + g-computation for marginal RD; conditional OR supportiveFDA 2023 final: marginal estimand for primary; mention HC3 sandwich SE
RCT, stratified randomisation (sex/region/severity)Include strata as covariates in logistic; the analytic decision is non-optionalKahan-Morris 2012: ignoring strata inflates Type-I error up to 30%
Common outcome (prevalence >10%) where RR is the policy quantityModified Poisson + HC1/HC3 OR log-binomial regressionAvoid OR misinterpretation; Zou 2004; cite EMA 2015 on covariate adjustment
Rare event (<5% prevalence) or separation observedFirth penalty + penalised LR test for p-valueHeinze-Schemper 2002; Wald p from Firth is liberal
Ordinal outcome, PO assumption supportableProportional odds; verify with Brant test (R brant::brant)Most efficient when PO holds; common in toxicity grading and PROs
Ordinal outcome, PO fails on one or two predictorsPartial PO model (R VGAM::vglm(..., cumulative(parallel=FALSE~X)))Salvages most efficiency; only the offending coefficient gets per-cut-point estimate
Ordinal outcome, PO fails widelyMultinomial logisticWorst case; loses ordering info but valid
Single arm observational with strong confoundingLogistic adjusted + g-computation + propensity weightingDoubly robust; cite Hernan-Robins; consider TMLE
Binary endpoint, longitudinal repeated measuresGEE or generalised linear mixed modelSandwich SE for GEE; mixed-model OR is subject-specific not marginal

Standard Workflow

Goal: Fit a covariate-adjusted logistic regression for a binary clinical endpoint with explicit reference category and pre-specified covariates.

Approach: Use the formula API for automatic categorical handling and explicit reference; report both the conditional log-OR and the marginal RD via g-computation.

python
import statsmodels.formula.api as smf
import pandas as pd
import numpy as np
# CRITICAL: set reference category explicitly. statsmodels default is alphabetical,
# so 'Active' sorts before 'Placebo' and the OR direction silently flips.
model = smf.logit(
'outcome ~ C(ARM, Treatment(reference="Placebo")) + age + C(sex) + baseline_score',
data=df
).fit()
# Conditional ORs (Wald)
or_table = pd.DataFrame({
'OR': np.exp(model.params),
'Lower_CI': np.exp(model.conf_int()[0]),
'Upper_CI': np.exp(model.conf_int()[1]),
'p_value': model.pvalues
})
# Marginal RD via g-computation (the FDA 2023-recommended primary estimand):
df_active = df.assign(ARM='Active')
df_placebo = df.assign(ARM='Placebo')
risk_active = model.predict(df_active).mean()
risk_placebo = model.predict(df_placebo).mean()
marginal_rd = risk_active - risk_placebo
# For SE, use influence-function or bootstrap; see RobinCar / marginaleffects in R

The reference-category trap is the single most common silent bug. smf.logit('y ~ C(ARM)') uses alphabetical ordering, so ARM='Active' becomes 1 and ARM='Placebo' becomes 0 -- but with ARM=['Active','Placebo','Control'], 'Active' is the reference and 'Placebo' is the comparison. Always pass Treatment(reference="Placebo") or equivalent. R glm(y ~ relevel(ARM, ref='Placebo')).

Marginal vs Conditional Estimand -- The FDA 2023 Pivot

The single most important methodological shift in clinical biostatistics 2020-2025. Permutt 2020 established and FDA 2023 codified: the maximum-likelihood coefficient on Z in glm(Y ~ Z + X, family=binomial) is the conditional log-OR -- the OR comparing Z=1 to Z=0 holding X fixed. Due to OR non-collapsibility, this is a different parameter than the marginal log-OR (the OR comparing the entire treated population to the entire control population), even under perfect randomisation.

The FDA 2023 final guidance ("Adjusting for Covariates in Randomized Clinical Trials," May 2023) endorses covariate-adjusted nonlinear-model analysis provided the analyst targets a marginal estimand. Reporting the conditional OR from a multivariable logistic regression as "the treatment effect" silently changes the estimand from what was pre-specified.

G-computation / Standardisation
python
# Marginal effects on three scales via g-computation:
df_z1 = df.assign(ARM='Active')
df_z0 = df.assign(ARM='Placebo')
p_z1 = model.predict(df_z1)
p_z0 = model.predict(df_z0)
marg_p1 = p_z1.mean()
marg_p0 = p_z0.mean()
marg_rd = marg_p1 - marg_p0
marg_rr = marg_p1 / marg_p0
marg_or = (marg_p1 / (1 - marg_p1)) / (marg_p0 / (1 - marg_p0))

For valid SE: the delta-method/influence-function variance and HC3 sandwich are required. Python marginaleffects v0.0.13+ implements this via marginaleffects.avg_comparisons(model, variables='ARM', vcov='HC3'). R is more mature: marginaleffects::avg_comparisons (Arel-Bundock-Greifer-Heiss 2024 JSS 111:9), RobinCar (purpose-built for FDA 2023), riskCommunicator.

Tsiatis et al 2008 robustness guarantee: under randomisation Z ⊥ X, the g-computation marginal estimator is consistent for the marginal ATE even if the outcome model is misspecified. Efficiency depends on model quality; consistency does not. This is why FDA 2023 accepts the marginal RD via g-computation without requiring proof of correct logistic mean structure.

Reporting template (post-FDA-2023):

"Primary estimand: marginal risk difference of -8.5 percentage points (95% CI -12.7 to -4.2, HC3 SE), computed by g-computation/standardisation from a logistic regression adjusted for age, sex, and baseline severity. Supportive: conditional OR 0.48 (95% CI 0.34-0.67, Wald) from the same model."

Modified Poisson for Common Outcomes -- Direct RR

When prevalence > 10% and the policy quantity is RR (not OR), modified Poisson with sandwich SE is the de facto modern standard (Zou 2004 AJE 159:702):

python
import statsmodels.api as sm
import numpy as np
X = sm.add_constant(df[['treatment', 'age', 'baseline_score']])
poisson_model = sm.GLM(df['outcome'], X, family=sm.families.Poisson()).fit(cov_type='HC1')
rr = np.exp(poisson_model.params)
rr_ci = np.exp(poisson_model.conf_int())

cov_type='HC1' corrects the over-dispersion that Poisson inherently assumes. Without it the variance is wrong because binary data are NOT Poisson. For n < 250, HC3 is preferred (Long-Ervin 2000). What postdocs argue about: modified Poisson vs log-binomial -- log-binomial directly models RR but frequently fails to converge when predicted risk approaches 1; modified Poisson always converges but is marginally less efficient when log-binomial works.

Proportional Odds and Brant Test

Proportional odds (PO) assumption: the effect of each predictor is constant across all cut-points of the ordinal outcome. Must be tested or the model parameters are invalid.

python
from statsmodels.miscmodels.ordinal_model import OrderedModel
from statsmodels.api import MNLogit
import pandas as pd
df['severity'] = pd.Categorical(df['severity'], categories=['mild', 'moderate', 'severe'], ordered=True)
po_model = OrderedModel.from_formula('severity ~ treatment + age', data=df, distr='logit').fit(method='bfgs', disp=0)
mn_model = MNLogit.from_formula('severity ~ treatment + age', data=df).fit(disp=0)
# LR test for PO vs MN (omnibus)
lr_stat = 2 * (mn_model.llf - po_model.llf)
lr_df = mn_model.df_model - po_model.df_model
from scipy.stats import chi2
lr_p = 1 - chi2.cdf(lr_stat, lr_df)
# Per-coefficient Brant test in R: brant::brant(po_model_object)
# The Brant test localises which predictor(s) violate PO -- essential before deciding on partial PO

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
99
Repository forks
11
7-day trend score
28

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/swaruplab/operon/clinical-biostatistics-logistic-regression/badge)](https://verified-skill.com/skills/swaruplab/operon/clinical-biostatistics-logistic-regression)

Something wrong with this skill or its page? Tell us.