Skip to content

DRegression models · regression.gee

Generalized estimating equations (GEE)

What is the population-average effect of predictors when rows are correlated within clusters?

Marginal (population-average) regression for clustered or repeated data: Gaussian, logistic or Poisson mean models with an independence, exchangeable or AR(1) working correlation (the order within each cluster comes from a time column or the row order); robust ("sandwich") standard errors stay valid even if the working correlation is wrong. Coefficients (and odds or rate ratios) with Wald tests and intervals, joint Wald tests per predictor, the estimated correlation and scale.

Verified in Python and R Python and R agree to 10 decimals

A real result

Example “Dietox exchangeable”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Generalized estimating equationsRecorded · Python and R agreeRecorded 2026-11-17 · 63 values compared · largest relative difference 7.2e-16
R

Wald χ²(1) = 7577.49, p < .001

Wald χ² (all predictors)
8244.07
p
< .001
Scale φ
48.378
Correlation α
0.7672

Plots

CoefficientsHow large are several estimates, how precise, and which exclude the null?
View data
EstimatehighTermlow
6.9427.098week6.785
−0.75752.253copper: Cu035−3.768
1.7955.360copper: Cu175−1.770
2.0495.663vitamin E: Evit100−1.565
−1.1032.515vitamin E: Evit200−4.721

Assumptions

  • Enough clusters — 72 clusters.
  • Working correlation — Estimated exchangeable correlation α = 0.767; robust standard errors stay valid if this structure is wrong.

Coefficients (robust standard errors)

TermBRobust SEzp95% CI low95% CI high
(Intercept)15.0921.42210.613< .00112.30417.879
week6.9420.079787.049< .0016.7857.098
copper: Cu035−0.75751.536−0.4932.622−3.7682.253
copper: Cu1751.7951.8190.9867.324−1.7705.360
vitamin E: Evit1002.0491.8441.111.266−1.5655.663
vitamin E: Evit200−1.1031.846−0.5974.550−4.7212.515

Population-average effects; Wald z tests with sandwich standard errors (geepack's san.se).

Joint Wald tests of each predictor

TermWald χ²dfp
week7577.491< .001
copper1.7762.412
vitamin E3.7002.157
  • 2 of 861 rows were left out because a value was missing.
  • Gaussian mean model, exchangeable working correlation, rows ordered by pig and week; scale φ = Σ r² / N as geepack.
Python

Wald χ²(1) = 7577.49, p < .001

Wald χ² (all predictors)
8244.07
p
< .001
Scale φ
48.378
Correlation α
0.7672

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Enough clusters — 72 clusters.
  • Working correlation — Estimated exchangeable correlation α = 0.767; robust standard errors stay valid if this structure is wrong.

Coefficients (robust standard errors)

TermBRobust SEzp95% CI low95% CI high
(Intercept)15.0921.42210.613< .00112.30417.879
week6.9420.079787.049< .0016.7857.098
copper: Cu035−0.75751.536−0.4932.622−3.7682.253
copper: Cu1751.7951.8190.9867.324−1.7705.360
vitamin E: Evit1002.0491.8441.111.266−1.5655.663
vitamin E: Evit200−1.1031.846−0.5974.550−4.7212.515

Population-average effects; Wald z tests with sandwich standard errors (geepack's san.se).

Joint Wald tests of each predictor

TermWald χ²dfp
week7577.491< .001
copper1.7762.412
vitamin E3.7002.157
  • 2 of 861 rows were left out because a value was missing.
  • Gaussian mean model, exchangeable working correlation, rows ordered by pig and week; scale φ = Σ r² / N as geepack.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Dietox exchangeables1_dietox · cluster: pig · order: week · outcome: weight · predictors: week, copper, vitamin E
  • Dietox ar1s1_dietox · cluster: pig · order: week · outcome: weight · predictors: week, copper
  • Ohio logistic ar1s1_ohio · cluster: child · order: age · outcome: wheeze · predictors: age, smoking mother
  • Ohio logistic independences1_ohio · cluster: child · outcome: wheeze · predictors: age, smoking mother
  • Ticks poissons1_ticks · cluster: location · outcome: ticks · predictors: year, height (z)
  • Degenerate constants1_dietox · cluster: pig · order: week · outcome: weight · predictors: week, copper, vitamin E
  • Degenerate n1s1_dietox · cluster: pig · order: week · outcome: weight · predictors: week, copper, vitamin E
  • Degenerate single levels1_dietox · cluster: pig · order: week · outcome: weight · predictors: week, copper, vitamin E

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Study design: independent / paired / repeated / clustered · Statistics Guide · Step 0 — Prepare your data
  • Repeated / clustered: mixed models, GEE · Statistics Guide · D — Predict an outcome
  • Independence · Statistics Guide · Step 2 — Check assumptions
  • Generalized models · Statistics Guide · Step 3 — If assumptions are violated

What you need

Outcomenumeric / boolean / categorical · 1 column
Numeric (Gaussian or counts) or yes/no (logistic).
Predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
Columns used to explain or predict the outcome.
Clustercategorical / numeric / boolean · 1 column
The unit whose rows are correlated (subject, family, site).
Time / order within clusternumeric / temporal · 0–1 column
Sorts rows within each cluster (AR(1) uses the positions 1, 2, … in this order).

Choices you make

statistics

Mean modeldefault gaussian

The mean model: Gaussian for numbers, logistic for yes/no, Poisson for counts.

  • Gaussian (identity link)(default) — Identity link for a numeric outcome; effects read in the outcome's units.
  • Logistic (binary outcome) — Logit link for a yes/no outcome; effects read as population-average odds ratios.
  • Poisson (log link, counts) — Log link for counts; effects read as population-average rate ratios.
Working correlationdefault exchangeable

The robust standard errors are valid for any choice; a good choice makes the estimates more precise.

  • Exchangeable (same correlation for every pair)(default) — Assumes every pair in a cluster is equally correlated; good for people within a site or family.
  • AR(1) (decays with distance in time) — Assumes correlation fades with distance in time; good for evenly spaced repeated measures.
  • Independence — Works as if rows in a cluster were uncorrelated, with robust errors still valid; a safe fallback.
Interactionsdefault none

Add interaction terms so the effect of one predictor can depend on the value of another.

  • None (main effects only)(default) — Fits main effects only; the usual starting point and the easiest to read.
  • First two predictors (A × B) — Adds the A × B term for the first two predictors; pick it when you expect one effect to depend on the other.
  • All pairs of predictors — Adds every two-way term; uses many coefficients, so pick it with plenty of rows and a reason to look.

hypothesis

Event (modeled level)default —

Logistic models: the outcome level whose probability is modeled (default: the second level, true for yes/no).

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Enough clusters

    Sandwich standard errors need many clusters (roughly 40 or more); with fewer they are too small.

  • Working correlation

    The estimated within-cluster correlation; robust SEs stay valid if it is misspecified.

What it reports

  • Tests: First predictor (robust Wald test)
n
How many independent units the analysis used; it sets precision and power.
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
n_clusters
How many independent units the analysis used; it sets precision and power.
max_cluster_size
Number of rows in the biggest cluster (such as one subject's repeated measurements) used by the GEE.
family
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
corstr
GEE's stated guess at how rows in a cluster relate. A wrong guess costs precision, and robust errors stay valid.
scale
Stretches or shrinks a fitted distribution without changing its form, so larger means more spread.
alpha
The false-positive rate you accept before looking at the data, usually 0.05.
wald
Tests a parameter by dividing its estimate by its standard error; quick, but unreliable near boundaries or with separation.
wald_df
How much independent information is left to estimate variability after fitting the model.
wald_p
Tests a parameter by dividing its estimate by its standard error; quick, but unreliable near boundaries or with separation.
focal_chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
focal_df
How much independent information is left to estimate variability after fitting the model.
focal_p
How surprising your data would be if the null hypothesis were true, as a probability.
converged
Whether an iterative fit found a stable solution; warnings mean estimates may be unreliable.
n_params
How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.
max_interaction_order
The most factors combined in one term of the model: 1 means main effects only, 2 two-way interactions.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Per group, level or term: coef[<term>], se[…], z[…], p[…], ci_low[…], ci_high[…], ratio[…], ratio_ci_low[…], ratio_ci_high[…], chi2[<predictor>], chi2_df[…], chi2_p[…]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses geepack, nanoparquet, codesplashr.

Default traps between the two languages

  • statsmodels' GEE estimates the scale with N − p degrees of freedom and the exchangeable/AR(1) correlations with other moment formulas, so the Python engine solves geepack's estimating equations (codesplash.stats.gee): φ = Σr²/N, exchangeable α = mean within-cluster product of Pearson residuals / φ, AR(1) α the least-squares solution over all within-cluster pairs at their distance. Both engines iterate to |Δβ| < 1e-12 (geeglm's default stops at 1e-4).
Python

The exact script CodeSplash ran for example “Dietox exchangeable” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Generalized estimating equations (GEE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.gee 1.0.1 · spec 9b6eb47a5c09ccde
# Dataset: s1_dietox (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash.stats import gee as csgee  # geepack's estimating equations (statsmodels' GEE uses other scale/α formulas)
from codesplash.stats import regression as csreg
from codesplash.stats.mixed import term_blocks  # design columns of each predictor (joint tests)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s1_dietox.parquet", columns=["weight", "week", "copper", "vitamin E", "pig"])
n_input = len(df)
df["copper"] = pd.Categorical(df["copper"], categories=["Cu000", "Cu035", "Cu175"])  # stored level order
df["vitamin E"] = pd.Categorical(df["vitamin E"], categories=["Evit000", "Evit100", "Evit200"])  # stored level order
df["pig"] = pd.Categorical(df["pig"], categories=["4601", "4602", "4603", "4605", "4641", "4643", "4645", "4756", "4757", "4759", "4760", "4813", "4814", "4815", "4817", "4854", "4856", "4857", "4858", "5389", "5392", "5497", "5500", "5501", "5502", "5524", "5527", "5528", "5578", "5581", "5582", "5850", "5851", "5852", "5862", "5865", "5866", "6055", "6056", "6057", "6058", "6207", "6208", "6211", "6284", "6287", "6288", "6430", "6432", "6433", "6909", "6910", "6912", "8049", "8050", "8051", "8053", "8139", "8141", "8142", "8144", "8191", "8192", "8193", "8195", "8269", "8270", "8271", "8273", "8437", "8439", "8442"])  # stored level order
df = df.dropna(subset=["weight", "week", "copper", "vitamin E", "pig"])  # listwise deletion over the analysis columns
df["copper"] = df["copper"].cat.remove_unused_categories()
df["vitamin E"] = df["vitamin E"].cat.remove_unused_categories()
df["pig"] = df["pig"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["weight", "week", "copper", "vitamin E", "pig"])  # infinite values stop the run (registry/errors.yaml)

# %% Data: clusters contiguous, ordered in time
outcome = "weight"
predictors = ["week", "copper", "vitamin E"]
cluster = "pig"
order = "week"
family = "gaussian"  # gaussian | binomial | poisson
corstr = "exchangeable"  # independence | exchangeable | ar1
interactions = "none"
conf = 0.95
df = df.sort_values([cluster] + ([order] if order else []), kind="stable").reset_index(drop=True)
if isinstance(df[outcome].dtype, pd.CategoricalDtype):
    levels_y = [str(x) for x in df[outcome].cat.categories]
    if family != "binomial":
        raise ValueError(f"{outcome} is categorical: use the logistic mean model with exactly two levels (found {len(levels_y)}).")
    if len(levels_y) != 2:
        cs.cs_error("CS_E_GROUP_COUNT", column=outcome, expected=2, k=len(levels_y))
    event = levels_y[1]  # default: the second stored level ("true" for yes/no)
    y = (df[outcome].astype(str) == event).to_numpy(dtype=float)
else:
    event = None
    y = df[outcome].to_numpy(dtype=float)
    if family == "binomial" and not np.all(np.isin(y, (0.0, 1.0))):
        raise ValueError(f"{outcome} must be 0/1 (or yes/no) for a logistic GEE.")
    if family == "poisson" and ((y < 0).any() or (np.abs(y - np.round(y)) > 1e-9).any()):
        raise ValueError(f"{outcome} must hold counts (non-negative whole numbers) for a Poisson GEE.")
X = csreg.design_matrix(df, predictors, interactions)
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
cs.check_rows(len(df), X.shape[1] + 1, "A GEE model")  # more rows than coefficients
for col in [outcome] + predictors:
    check_not_constant(df[col], col)  # one value (or one level with data) is no variation
check_groups(df[cluster], cluster, minimum=2)  # the robust covariance needs several clusters
if np.linalg.matrix_rank(X.to_numpy()) < X.shape[1]:
    cs.cs_error("CS_E_COLLINEAR")
terms = list(X.columns)
n, k = X.shape
ids = df[cluster].cat.codes.to_numpy() if isinstance(df[cluster].dtype, pd.CategoricalDtype) else df[cluster].to_numpy()

# %% Fit (Fisher scoring to |Δβ| < 1e-12; robust sandwich covariance)
fit = csgee.gee_fit(y, X.to_numpy(), ids, family, corstr, tol=1e-12)
b = fit.beta
se = np.sqrt(np.diag(fit.vcov))
zval = b / se
pval = 2 * stats.norm.sf(np.abs(zval))
crit = stats.norm.ppf(1 - (1 - conf) / 2)
ratio = family in ("binomial", "poisson")
values = {}
coefs = []
for j, t in enumerate(terms):
    row = {"term": t, "estimate": float(b[j]), "se": float(se[j]), "z": float(zval[j]), "p": float(pval[j]),
           "ci_low": float(b[j] - crit * se[j]), "ci_high": float(b[j] + crit * se[j])}
    if ratio:
        row.update({"ratio": float(np.exp(b[j])), "ratio_ci_low": float(np.exp(row["ci_low"])), "ratio_ci_high": float(np.exp(row["ci_high"]))})
    coefs.append(row)
    values.update({f"{key}[{t}]": row["estimate" if key == "coef" else key] for key in ("coef", "se", "z", "p", "ci_low", "ci_high")})
    if ratio:
        values.update({f"{key}[{t}]": row[key] for key in ("ratio", "ratio_ci_low", "ratio_ci_high")})


def wald(idx):
    bb = b[idx]
    V = fit.vcov[np.ix_(idx, idx)]
    w = float(bb @ np.linalg.solve(V, bb))
    return w, len(idx), float(stats.chi2.sf(w, len(idx)))


slopes_idx = [j for j, t in enumerate(terms) if t != "(Intercept)"]
wald_all, wald_df, wald_p = wald(slopes_idx)
effects = []
for name, idx in term_blocks(terms, predictors, csreg.interaction_pairs(len(predictors), interactions)):
    w, d, pw = wald(idx)
    effects.append({"term": name, "chi2": w, "df": d, "p": pw})
    values.update({f"chi2[{name}]": w, f"chi2_df[{name}]": float(d), f"chi2_p[{name}]": pw})
sizes = np.diff(np.r_[np.flatnonzero(np.r_[True, ids[1:] != ids[:-1]]), n])
values.update({"n": n, "k": k, "n_clusters": fit.n_clusters, "max_cluster_size": int(sizes.max()), "family": family, "corstr": corstr,
               "scale": fit.phi, "alpha": fit.alpha, "wald": wald_all, "wald_df": float(wald_df), "wald_p": wald_p,
               "focal_chi2": effects[0]["chi2"], "focal_df": float(effects[0]["df"]), "focal_p": effects[0]["p"],
               "converged": fit.converged, "n_params": k, "max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1,
               "missing_share": n_dropped / n_input if n_input else 0.0})

# %% Assumptions
assumptions = [
    {"key": "clusters", "label": "Enough clusters", "status": "warn" if fit.n_clusters < 40 else "pass", "statistic": fit.n_clusters,
     "detail": f"{fit.n_clusters} clusters" + ("; with fewer than about 40, sandwich standard errors are too small — interpret p-values cautiously." if fit.n_clusters < 40 else ".")},
    {"key": "correlation", "label": "Working correlation", "status": "info",
     "detail": ("Independence working correlation: estimates equal the ordinary GLM; only the standard errors account for clustering." if corstr == "independence"
                else f"Estimated {'exchangeable' if corstr == 'exchangeable' else 'AR(1)'} correlation α = {fit.alpha:.3f}; robust standard errors stay valid if this structure is wrong.")},
]
if not fit.converged:
    warnings.append("The estimating equations did not converge in 200 iterations.")

# %% Result
pct = f"{conf:.0%}"
fam_name = {"gaussian": "Gaussian", "binomial": "Logistic", "poisson": "Poisson"}[family]
cor_name = {"independence": "independence", "exchangeable": "exchangeable", "ar1": "AR(1)"}[corstr]
e0 = effects[0]
summary = (f"{fam_name} GEE of {outcome}" + (f" (event: {event})" if event else "") + f" with an {cor_name} working correlation "
           f"(n = {n}, {fit.n_clusters} clusters): {e0['term']}: Wald χ²({e0['df']}) = {e0['chi2']:.2f}, {cs.fmt_p(e0['p'])} (robust SEs).")
columns = [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"},
           {"key": "se", "label": "Robust SE", "type": "number"}, {"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}]
if ratio:
    rl = "Odds ratio" if family == "binomial" else "Rate ratio"
    columns += [{"key": "ratio", "label": rl, "type": "number"}, {"key": "ratio_ci_low", "label": f"{pct} CI low", "type": "number"},
                {"key": "ratio_ci_high", "label": f"{pct} CI high", "type": "number"}]
else:
    columns += [{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}]
slopes = [c for c in coefs if c["term"] != "(Intercept)"]
chart = cs.chart("coef", "forest", "Odds ratios" if family == "binomial" else ("Rate ratios" if family == "poisson" else "Coefficients"), {
    "label": cs.col("Term", [c["term"] for c in slopes], kind="categorical"),
    "estimate": cs.col("Estimate", [c["ratio"] if ratio else c["estimate"] for c in slopes]),
    "low": cs.col("low", [c["ratio_ci_low"] if ratio else c["ci_low"] for c in slopes]),
    "high": cs.col("high", [c["ratio_ci_high"] if ratio else c["ci_high"] for c in slopes])},
    controls={"reference": 1, "log": True} if ratio else {"reference": 0})
cs.publish({
    "method": "regression.gee",
    "methodVersion": "1.0.1",
    "title": "Generalized estimating equations",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"Wald χ²({e0['df']}) = {e0['chi2']:.2f}, {cs.fmt_p(e0['p'])}",
    "statistics": [{"key": "wald", "label": "Wald χ² (all predictors)", "value": wald_all}, {"key": "wald_p", "label": "p", "value": wald_p, "format": "p"},
                   {"key": "scale", "label": "Scale φ", "value": fit.phi}] + ([{"key": "alpha", "label": "Correlation α", "value": fit.alpha}] if fit.alpha is not None else []),
    "tables": [
        {"key": "coefficients", "title": "Coefficients (robust standard errors)", "columns": columns, "rows": coefs,
         "note": "Population-average effects; Wald z tests with sandwich standard errors (geepack's san.se)."},
        {"key": "effects", "title": "Joint Wald tests of each predictor", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "chi2", "label": "Wald χ²", "type": "number"},
            {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"}], "rows": effects},
    ],
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"{fam_name} mean model, {cor_name} working correlation, rows ordered by {cluster}" + (f" and {order}" if order else "") + "; scale φ = Σ r² / N as geepack."],
    "charts": [chart] if slopes else [],
    "values": values,
})
R

The exact script CodeSplash ran for example “Dietox exchangeable” · R version 4.5.1 (2025-06-13)

# Generalized estimating equations (GEE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.gee 1.0.1 · spec 9b6eb47a5c09ccde
# Dataset: s1_dietox (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(geepack))

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_dietox.parquet", col_select = c("weight", "week", "copper", "vitamin E", "pig")))
n_input <- nrow(df)
df[["copper"]] <- factor(df[["copper"]], levels = c("Cu000", "Cu035", "Cu175"))  # stored level order
df[["vitamin E"]] <- factor(df[["vitamin E"]], levels = c("Evit000", "Evit100", "Evit200"))  # stored level order
df[["pig"]] <- factor(df[["pig"]], levels = c("4601", "4602", "4603", "4605", "4641", "4643", "4645", "4756", "4757", "4759", "4760", "4813", "4814", "4815", "4817", "4854", "4856", "4857", "4858", "5389", "5392", "5497", "5500", "5501", "5502", "5524", "5527", "5528", "5578", "5581", "5582", "5850", "5851", "5852", "5862", "5865", "5866", "6055", "6056", "6057", "6058", "6207", "6208", "6211", "6284", "6287", "6288", "6430", "6432", "6433", "6909", "6910", "6912", "8049", "8050", "8051", "8053", "8139", "8141", "8142", "8144", "8191", "8192", "8193", "8195", "8269", "8270", "8271", "8273", "8437", "8439", "8442"))  # stored level order
df <- df[stats::complete.cases(df[c("weight", "week", "copper", "vitamin E", "pig")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("weight", "week", "copper", "vitamin E", "pig"))  # infinite values stop the run (registry/errors.yaml)

# %% Data: clusters contiguous, ordered in time
outcome <- "weight"
predictors <- c("week", "copper", "vitamin E")
cluster <- "pig"
order_col <- "week"
family <- "gaussian"  # gaussian | binomial | poisson
corstr <- "exchangeable"  # independence | exchangeable | ar1
interactions <- "none"
conf <- 0.95
df <- df[if (is.null(order_col)) order(df[[cluster]]) else order(df[[cluster]], df[[order_col]]), , drop = FALSE]
rownames(df) <- NULL
event <- NULL
if (is.factor(df[[outcome]])) {
  if (family != "binomial") stop(sprintf("%s is categorical: use the logistic mean model with exactly two levels (found %d).", outcome, nlevels(df[[outcome]])))
  if (nlevels(df[[outcome]]) != 2) cs_error("CS_E_GROUP_COUNT", column = outcome, expected = 2, k = nlevels(df[[outcome]]))
  event <- levels(df[[outcome]])[2]  # default: the second stored level ("true" for yes/no)
  df$.cs_y <- as.numeric(as.character(df[[outcome]]) == event)
} else {
  df$.cs_y <- as.numeric(df[[outcome]])
  if (family == "binomial" && !all(df$.cs_y %in% c(0, 1))) stop(sprintf("%s must be 0/1 (or yes/no) for a logistic GEE.", outcome))
  if (family == "poisson" && (any(df$.cs_y < 0) || any(abs(df$.cs_y - round(df$.cs_y)) > 1e-9))) stop(sprintf("%s must hold counts (non-negative whole numbers) for a Poisson GEE.", outcome))
}
terms <- cs_design_labels(df, predictors, interactions)
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_rows(nrow(df), length(terms) + 1, "A GEE model")  # more rows than coefficients
for (col in c(outcome, predictors)) cs_check_not_constant(df[[col]], col)  # one value (or one level with data) is no variation
cs_check_groups(df[[cluster]], cluster, minimum = 2)  # the robust covariance needs several clusters
df$.cs_id <- as.integer(factor(df[[cluster]], levels = unique(df[[cluster]])))
fml <- cs_model_formula(".cs_y", predictors, interactions)
fam <- switch(family, gaussian = gaussian(), binomial = binomial(), poisson = poisson())

# %% Fit (geepack; tolerance tightened from geeglm's default 1e-4)
fit <- geeglm(fml, family = fam, data = df, id = .cs_id, corstr = corstr, control = geese.control(epsilon = 1e-12, maxit = 200))
b <- unname(coef(fit))
if (anyNA(b) || length(b) != length(terms)) cs_error("CS_E_COLLINEAR")
V <- unname(vcov(fit))  # robust sandwich (san.se)
n <- nrow(df)
k <- length(b)
se <- sqrt(diag(V))
zval <- b / se
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)
crit <- qnorm(1 - (1 - conf) / 2)
ratio <- family %in% c("binomial", "poisson")
values <- list()
coefs <- list()
for (j in seq_len(k)) {
  t <- terms[j]
  row <- list(term = t, estimate = b[j], se = se[j], z = zval[j], p = pval[j], ci_low = b[j] - crit * se[j], ci_high = b[j] + crit * se[j])
  if (ratio) row <- c(row, list(ratio = exp(b[j]), ratio_ci_low = exp(row$ci_low), ratio_ci_high = exp(row$ci_high)))
  coefs[[j]] <- row
  for (key in c("coef", "se", "z", "p", "ci_low", "ci_high")) values[[sprintf("%s[%s]", key, t)]] <- if (key == "coef") row$estimate else row[[key]]
  if (ratio) for (key in c("ratio", "ratio_ci_low", "ratio_ci_high")) values[[sprintf("%s[%s]", key, t)]] <- row[[key]]
}
wald <- function(idx) {
  bb <- b[idx]
  w <- as.numeric(t(bb) %*% solve(V[idx, idx, drop = FALSE], bb))
  list(chi2 = w, df = length(idx), p = pchisq(w, length(idx), lower.tail = FALSE))
}
all_w <- wald(which(terms != "(Intercept)"))
effects <- list()
blocks <- cs_mixed_term_blocks(terms, predictors, interactions)
for (name in names(blocks)) {
  w <- wald(blocks[[name]])
  effects[[length(effects) + 1]] <- list(term = name, chi2 = w$chi2, df = w$df, p = w$p)
  values[[sprintf("chi2[%s]", name)]] <- w$chi2; values[[sprintf("chi2_df[%s]", name)]] <- as.numeric(w$df); values[[sprintf("chi2_p[%s]", name)]] <- w$p
}
s <- summary(fit)
alpha <- if (corstr == "independence") NA else unname(s$corr$Estimate[1])
phi <- unname(s$dispersion$Estimate[1])
sizes <- as.vector(table(df$.cs_id))
n_clusters <- length(sizes)
values <- c(values, list(n = n, k = k, n_clusters = n_clusters, max_cluster_size = max(sizes), family = family, corstr = corstr,
                         scale = phi, alpha = alpha, wald = all_w$chi2, wald_df = as.numeric(all_w$df), wald_p = all_w$p,
                         focal_chi2 = effects[[1]]$chi2, focal_df = as.numeric(effects[[1]]$df), focal_p = effects[[1]]$p,
                         converged = isTRUE(fit$geese$error == 0), n_params = k,
                         max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1,
                         missing_share = if (n_input > 0) n_dropped / n_input else 0))

# %% Assumptions
assumptions <- list(
  list(key = "clusters", label = "Enough clusters", status = if (n_clusters < 40) "warn" else "pass", statistic = n_clusters,
       detail = paste0(sprintf("%d clusters", n_clusters), if (n_clusters < 40) "; with fewer than about 40, sandwich standard errors are too small — interpret p-values cautiously." else ".")),
  list(key = "correlation", label = "Working correlation", status = "info",
       detail = if (corstr == "independence") "Independence working correlation: estimates equal the ordinary GLM; only the standard errors account for clustering."
                else sprintf("Estimated %s correlation α = %.3f; robust standard errors stay valid if this structure is wrong.", if (corstr == "exchangeable") "exchangeable" else "AR(1)", alpha))
)
if (!isTRUE(values$converged)) warnings <- c(warnings, "The estimating equations did not converge in 200 iterations.")

# %% Result
pct <- sprintf("%.0f%%", conf * 100)
fam_name <- c(gaussian = "Gaussian", binomial = "Logistic", poisson = "Poisson")[[family]]
cor_name <- c(independence = "independence", exchangeable = "exchangeable", ar1 = "AR(1)")[[corstr]]
e0 <- effects[[1]]
summary <- sprintf("%s GEE of %s%s with an %s working correlation (n = %d, %d clusters): %s: Wald χ²(%d) = %.2f, %s (robust SEs).",
                   fam_name, outcome, if (!is.null(event)) sprintf(" (event: %s)", event) else "", cor_name, n, n_clusters, e0$term, as.integer(e0$df), e0$chi2, cs_fmt_p(e0$p))
columns <- list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B", type = "number"),
                list(key = "se", label = "Robust SE", type = "number"), list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"))
if (ratio) {
  rl <- if (family == "binomial") "Odds ratio" else "Rate ratio"
  columns <- c(columns, list(list(key = "ratio", label = rl, type = "number"), list(key = "ratio_ci_low", label = paste(pct, "CI low"), type = "number"),
                             list(key = "ratio_ci_high", label = paste(pct, "CI high"), type = "number")))
} else {
  columns <- c(columns, list(list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")))
}
slopes <- Filter(function(cf) cf$term != "(Intercept)", coefs)
pick <- function(key, alt) vapply(slopes, function(cf) if (ratio) cf[[key]] else cf[[alt]], 0)
charts <- if (length(slopes)) list(cs_chart("coef", "forest", if (family == "binomial") "Odds ratios" else if (family == "poisson") "Rate ratios" else "Coefficients", list(
  label = cs_col("Term", vapply(slopes, `[[`, "", "term"), kind = "categorical"), estimate = cs_col("Estimate", pick("ratio", "estimate")),
  low = cs_col("low", pick("ratio_ci_low", "ci_low")), high = cs_col("high", pick("ratio_ci_high", "ci_high"))),
  controls = if (ratio) list(reference = 1, log = TRUE) else list(reference = 0))) else list()
statistics <- list(list(key = "wald", label = "Wald χ² (all predictors)", value = all_w$chi2), list(key = "wald_p", label = "p", value = all_w$p, format = "p"),
                   list(key = "scale", label = "Scale φ", value = phi))
if (!is.na(alpha)) statistics[[length(statistics) + 1]] <- list(key = "alpha", label = "Correlation α", value = alpha)
cs_publish(list(
  method = "regression.gee",
  methodVersion = "1.0.1",
  title = "Generalized estimating equations",
  engine = cs_engine_info("geepack", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("Wald χ²(%d) = %.2f, %s", as.integer(e0$df), e0$chi2, cs_fmt_p(e0$p)),
  statistics = statistics,
  tables = list(
    list(key = "coefficients", title = "Coefficients (robust standard errors)", columns = columns, rows = coefs,
         note = "Population-average effects; Wald z tests with sandwich standard errors (geepack's san.se)."),
    list(key = "effects", title = "Joint Wald tests of each predictor", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "chi2", label = "Wald χ²", type = "number"),
      list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")), rows = effects)
  ),
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("%s mean model, %s working correlation, rows ordered by %s%s; scale φ = Σ r² / N as geepack.", fam_name, cor_name, cluster,
                       if (!is.null(order_col)) paste(" and", order_col) else "")),
  charts = charts,
  values = values
))

Sources

  • Liang, K.-Y., & Zeger, S. L. (1986). Longitudinal data analysis using generalized linear models. Biometrika, 73, 13–22.
  • Halekoh, U., Højsgaard, S., & Yan, J. (2006). The R package geepack for generalized estimating equations. Journal of Statistical Software, 15(2).

From the CodeSplash method registry · regression.gee v1.0.1.