Skip to content

GEE: population-average effects

Generalized estimating equations ask how the average outcome changes across a population, treat within-cluster correlation as a nuisance, and give standard errors that hold up even when your guess about that correlation is wrong.

Advanced ~11 min10 steps

What runs in CodeSplash

You will be able to

  • Say what a population-average effect is, and how it differs from a subject-specific one
  • Choose a working correlation, and read alpha
  • Explain why robust standard errors protect you when the working correlation is wrong
  • Decide between GEE and a mixed model

Read first

01

A different question

Read

A mixed model asks what happens to one person when their predictor changes. GEEGeneralized estimating equationsEstimates population-average effects on clustered data, with robust errors that allow for a wrong working correlation. asks how the average outcome differs across the population as the predictor changes. That's a population-averagePopulation-average effectHow the average outcome differs across a population. In logistic models it's closer to 1 than a subject-specific ratio. effect.

A health department deciding on a smoking policy wants that average. A clinician counseling one patient may want the other.

GEE doesn't model each cluster. It writes down the mean model you care about and treats within-cluster correlation as a nuisance to allow for.

02

The working correlation

Read

You give GEE a guess at how rows within a cluster relate. This working correlationWorking correlationGEE's stated guess at how rows in a cluster relate. A wrong guess costs precision, and robust errors stay valid. has three common forms:

  • Independence: no correlation is assumed.
  • Exchangeable: every pair in a cluster shares one correlation.
  • AR(1): correlation falls with the distance between rows in time.

The estimate is called α\alpha. For pigs weighed weekly, exchangeable gives α\alpha = 0.767. AR(1), with an interaction added, gives α\alpha = 0.937 between neighboring weeks.

03

How much does the guess matter?

Predict

Predict first

Four yearly wheeze checks on 537 children. You fit logistic GEE with an AR(1) working correlation, then with independence. How much does the robust test of age change?

Hardly at allModeratelyCompletely
Reveal

Hardly at all: AR(1) gives χ2\chi^2 = 6.41, p = .011, and independence gives χ2\chi^2 = 6.68, p = .010. The estimated α\alpha was 0.491.

04

Why robust errors save you

Read

GEE's standard errors are sandwich estimates, like the cluster-robustCluster-robust standard errorsStandard errors that allow any correlation within a cluster and assume independence between clusters. errors you've met. They use the residuals that clusters actually produce, instead of trusting the working correlation.

So a wrong guess costs some efficiency, but the standard errors stay valid. A better guess gets you narrower intervals, and the test stays honest either way, as long as there are enough clusters.

That protection is why you can't read the working correlation as a finding about the data.

05

Read the card

In the app
Generalized estimating equationsRecorded · Python and R agreeRecorded 2026-11-17 · 51 values compared
R

Wald χ²(1) = 6.41, p = .011

Wald χ² (all predictors)
8.286
p
.016
Scale φ
1.021
Correlation α
0.4910

Plots

Odds ratiosHow large are several estimates, how precise, and which exclude the null?
View data
EstimatehighTermlow
0.89150.9606age0.8273
1.2641.703smoking mother: true0.9384

Assumptions

  • Enough clusters — 537 clusters.
  • Working correlation — Estimated AR(1) correlation α = 0.491; robust standard errors stay valid if this structure is wrong.

Coefficients (robust standard errors)

TermBRobust SEzpOdds ratio90% CI low90% CI high
(Intercept)−1.9020.1153−16.505< .0010.14920.12350.1804
age−0.11490.0454−2.531.0110.89150.82730.9606
smoking mother: true0.23450.18121.294.1961.2640.93841.703

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

Joint Wald tests of each predictor

TermWald χ²dfp
age6.4071.011
smoking mother1.6751.196
  • Logistic mean model, AR(1) working correlation, rows ordered by child and age; scale φ = Σ r² / N as geepack.
The exact R script · R 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 9f9252d01103095c
# Dataset: s1_ohio (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_ohio.parquet", col_select = c("wheeze", "age", "smoking mother", "child")))
n_input <- nrow(df)
df[["wheeze"]] <- factor(df[["wheeze"]], levels = c("false", "true"))  # stored level order
df[["smoking mother"]] <- factor(df[["smoking mother"]], levels = c("false", "true"))  # stored level order
df <- df[stats::complete.cases(df[c("wheeze", "age", "smoking mother", "child")]), , 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("wheeze", "age", "smoking mother", "child"))  # infinite values stop the run (registry/errors.yaml)

# %% Data: clusters contiguous, ordered in time
outcome <- "wheeze"
predictors <- c("age", "smoking mother")
cluster <- "child"
order_col <- "age"
family <- "binomial"  # gaussian | binomial | poisson
corstr <- "ar1"  # independence | exchangeable | ar1
interactions <- "none"
conf <- 0.9
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
))
Python

Wald χ²(1) = 6.41, p = .011

Wald χ² (all predictors)
8.286
p
.016
Scale φ
1.021
Correlation α
0.4910

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

Assumptions

  • Enough clusters — 537 clusters.
  • Working correlation — Estimated AR(1) correlation α = 0.491; robust standard errors stay valid if this structure is wrong.

Coefficients (robust standard errors)

TermBRobust SEzpOdds ratio90% CI low90% CI high
(Intercept)−1.9020.1153−16.505< .0010.14920.12350.1804
age−0.11490.0454−2.531.0110.89150.82730.9606
smoking mother: true0.23450.18121.294.1961.2640.93841.703

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

Joint Wald tests of each predictor

TermWald χ²dfp
age6.4071.011
smoking mother1.6751.196
  • Logistic mean model, AR(1) working correlation, rows ordered by child and age; scale φ = Σ r² / N as geepack.
The exact Python script · Python 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 9f9252d01103095c
# Dataset: s1_ohio (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_ohio.parquet", columns=["wheeze", "age", "smoking mother", "child"])
n_input = len(df)
df["wheeze"] = pd.Categorical(df["wheeze"], categories=["false", "true"])  # stored level order
df["smoking mother"] = pd.Categorical(df["smoking mother"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["wheeze", "age", "smoking mother", "child"])  # listwise deletion over the analysis columns
df["wheeze"] = df["wheeze"].cat.remove_unused_categories()
df["smoking mother"] = df["smoking mother"].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, ["wheeze", "age", "smoking mother", "child"])  # infinite values stop the run (registry/errors.yaml)

# %% Data: clusters contiguous, ordered in time
outcome = "wheeze"
predictors = ["age", "smoking mother"]
cluster = "child"
order = "age"
family = "binomial"  # gaussian | binomial | poisson
corstr = "ar1"  # independence | exchangeable | ar1
interactions = "none"
conf = 0.9
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,
})

There are 2,148 rows, in clusters of at most 4. The ratio column has odds ratios on the population-average scale.

The joint test of all predictors gives p = .016. GEE has no likelihood, so there's no AIC, and effects use Wald tests with robust standard errors.

Compare the two predictors: which one's interval clears 1? Read the sizes before the p-values.

06

Why the two estimates differ

Reflect

Picture one S-shaped curve for each child, all with the same slope, shifted left and right. Now average them at each age. The result is flatter than any one of them.

So a GEE odds ratio usually sits closer to 1 than a mixed model's. The bigger the spread between children, the larger that gap. For a linear model with a normal outcome, the two coincide.

Which do your readers want: the change for one person, or the difference across a population?

07

GEE or mixed model?

Read
GEEMixed model
EffectPopulation averageSubject-specific
CorrelationA nuisance with robust errorsModeled through variances
Few clustersSandwich errors too smallVariances imprecise
Missing dataNeeds missing completely at randomValid under missing at random
New cluster's predictionNoYes
Group-level variationNot estimatedEstimated

Sandwich errors need many clusters, roughly 40 or more. That one's a common reason to choose a mixed model. Missing data is another.

08

Check your understanding

Checkpoint

Check yourself

A policy team asks how much lower the smoking rate would be across the country with a tax. Which target fits?

Show the answer

Answer: a

They care about the overall rate, not one person's odds. A subject-specific ratio can't be used as a population rate without further averaging.

Check yourself

Your true correlation is AR(1), but you chose exchangeable. What's the main cost?

Show the answer

Answer: c

With robust errors and enough clusters, a wrong working correlation costs precision, not validity.

Check yourself

You have 9 clinics, and want GEE. What's the main worry?

Show the answer

Answer: a

The sandwich estimates its correlation from the clusters themselves. With fewer than about 40, it tends to be too small, so p-values look better than they should.

Check yourself

On the same data, a logistic mixed model gives an odds ratio of 2.4. What would you expect from GEE?

Show the answer

Answer: a

Averaging over people flattens the curve, so population-average ratios sit closer to 1. They'd coincide in a linear model.

09

Fit yours

In the app

Set Outcome, Predictors and Cluster, plus a Time / order within cluster column if you pick AR(1). Choose Mean model, and start with an exchangeable Working correlation unless time order matters.

Python
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

df = pd.read_csv("s1_ohio.csv").rename(columns={"smoking mother": "smoke"})
df["wheeze"] = df["wheeze"].astype(int)
df["smoke"] = df["smoke"].astype(int)

fit = smf.gee("wheeze ~ age + smoke", groups="child", time="age", data=df,
              family=sm.families.Binomial(),
              cov_struct=sm.cov_struct.Autoregressive()).fit()
print(fit.summary())
print(fit.cov_struct.summary())
R
library(geepack)

df <- read.csv("s1_ohio.csv", check.names = FALSE)
names(df)[names(df) == "smoking mother"] <- "smoke"
df$wheeze <- as.integer(df$wheeze == "true")
df$smoke <- as.integer(df$smoke == "true")

fit <- geeglm(wheeze ~ age + smoke, id = child, data = df,
              family = binomial, corstr = "ar1")
summary(fit)
exp(coef(fit))  # population-average odds ratios

Different packages estimate α\alpha a little differently. CodeSplash follows geepack in both engines, so the statsmodels script can differ slightly from the card.

10

Recap

Recap
  • GEE targets the population-average effect, and treats correlation as a nuisance.
  • A wrong working correlation costs efficiency, while robust errors stay valid.
  • Its ratios usually sit closer to 1 than a mixed model's.
  • It needs many clusters, and it's less forgiving of missing data than a mixed model.

Concepts in this lesson