EProportions & counts · contingency.loglinear
Log-linear models for multiway tables
Which associations among three or more categorical variables are needed to explain their joint counts?
Hierarchical log-linear models fitted as Poisson regressions on every cell of the cross-table (empty cells included): independence, homogeneous association (all two-way terms), the saturated model, or backward elimination of the highest-order terms by likelihood-ratio tests. Reports the model's G² and Pearson X² against the saturated model, a likelihood-ratio test for every interaction in the final model, and adjusted residuals for each cell.
A real result
Example “Hair eye sex backward”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
G²(12, N = 592) = 11.76, p = .465
- G² (likelihood ratio)
- 11.764
- Pearson X²
- 11.771
- df
- 12
- p (G²)
- .465
- AIC
- 190.64
Plots
View data
| term | ΔG² |
|---|---|
| hair × eye | 146.44 |
| hair × sex | 8.093 |
Assumptions
- Enough expected counts — 16% of fitted cell counts are below 5 (smallest 2.41).
- Independent observations — Each subject is counted in one cell.
Backward elimination
| Step | Removed | ΔG² | df | p |
|---|---|---|---|---|
| 1 | hair × eye × sex | 6.761 | 9 | 0.6620 |
| 2 | eye × sex | 5.002 | 3 | 0.1716 |
Likelihood-ratio tests of the interactions in the final model
| Term | ΔG² | df | p |
|---|---|---|---|
| hair × eye | 146.44 | 9 | 4.806e-27 |
| hair × sex | 8.093 | 3 | 0.0441 |
Observed and fitted counts
| hair · eye · sex | Observed | Fitted | Adjusted residual |
|---|---|---|---|
| Black · Brown · Male | 32 | 35.259 | −1.300 |
| Brown · Brown · Male | 53 | 59.500 | −1.560 |
| Red · Brown · Male | 10 | 12.451 | −1.208 |
| Blond · Brown · Male | 3 | 2.535 | 0.3758 |
| Black · Blue · Male | 11 | 10.370 | 0.3122 |
| Brown · Blue · Male | 50 | 42 | 2.077 |
| Red · Blue · Male | 10 | 8.141 | 1.035 |
| Blond · Blue · Male | 30 | 34.047 | −1.704 |
| Black · Hazel · Male | 10 | 7.778 | 1.237 |
| Brown · Hazel · Male | 25 | 27 | −0.6044 |
| Red · Hazel · Male | 7 | 6.704 | 0.1766 |
| Blond · Hazel · Male | 5 | 3.622 | 0.9446 |
| Black · Green · Male | 3 | 2.593 | 0.3734 |
| Brown · Green · Male | 15 | 14.500 | 0.1959 |
| Red · Green · Male | 7 | 6.704 | 0.1766 |
| Blond · Green · Male | 8 | 5.795 | 1.227 |
| Black · Brown · Female | 36 | 32.741 | 1.300 |
| Brown · Brown · Female | 66 | 59.500 | 1.560 |
| Red · Brown · Female | 16 | 13.549 | 1.208 |
| Blond · Brown · Female | 4 | 4.465 | −0.3758 |
| Black · Blue · Female | 9 | 9.630 | −0.3122 |
| Brown · Blue · Female | 34 | 42 | −2.077 |
| Red · Blue · Female | 7 | 8.859 | −1.035 |
| Blond · Blue · Female | 64 | 59.953 | 1.704 |
| Black · Hazel · Female | 5 | 7.222 | −1.237 |
| Brown · Hazel · Female | 29 | 27 | 0.6044 |
| Red · Hazel · Female | 7 | 7.296 | −0.1766 |
| Blond · Hazel · Female | 5 | 6.378 | −0.9446 |
| Black · Green · Female | 2 | 2.407 | −0.3734 |
| Brown · Green · Female | 14 | 14.500 | −0.1959 |
| Red · Green · Female | 7 | 7.296 | −0.1766 |
| Blond · Green · Female | 8 | 10.205 | −1.227 |
- Model (generating class): [hair × eye] [hair × sex]. Every cell of the 4 × 4 × 2 table is fitted, empty cells included.
G²(12, N = 592) = 11.76, p = .465
- G² (likelihood ratio)
- 11.764
- Pearson X²
- 11.771
- df
- 12
- p (G²)
- .465
- AIC
- 190.64
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough expected counts — 16% of fitted cell counts are below 5 (smallest 2.41).
- Independent observations — Each subject is counted in one cell.
Backward elimination
| Step | Removed | ΔG² | df | p |
|---|---|---|---|---|
| 1 | hair × eye × sex | 6.761 | 9 | 0.6620 |
| 2 | eye × sex | 5.002 | 3 | 0.1716 |
Likelihood-ratio tests of the interactions in the final model
| Term | ΔG² | df | p |
|---|---|---|---|
| hair × eye | 146.44 | 9 | 4.806e-27 |
| hair × sex | 8.093 | 3 | 0.0441 |
Observed and fitted counts
| hair · eye · sex | Observed | Fitted | Adjusted residual |
|---|---|---|---|
| Black · Brown · Male | 32 | 35.259 | −1.300 |
| Black · Brown · Female | 36 | 32.741 | 1.300 |
| Black · Blue · Male | 11 | 10.370 | 0.3122 |
| Black · Blue · Female | 9 | 9.630 | −0.3122 |
| Black · Hazel · Male | 10 | 7.778 | 1.237 |
| Black · Hazel · Female | 5 | 7.222 | −1.237 |
| Black · Green · Male | 3 | 2.593 | 0.3734 |
| Black · Green · Female | 2 | 2.407 | −0.3734 |
| Brown · Brown · Male | 53 | 59.500 | −1.560 |
| Brown · Brown · Female | 66 | 59.500 | 1.560 |
| Brown · Blue · Male | 50 | 42.000 | 2.077 |
| Brown · Blue · Female | 34 | 42.000 | −2.077 |
| Brown · Hazel · Male | 25 | 27.000 | −0.6044 |
| Brown · Hazel · Female | 29 | 27.000 | 0.6044 |
| Brown · Green · Male | 15 | 14.500 | 0.1959 |
| Brown · Green · Female | 14 | 14.500 | −0.1959 |
| Red · Brown · Male | 10 | 12.451 | −1.208 |
| Red · Brown · Female | 16 | 13.549 | 1.208 |
| Red · Blue · Male | 10 | 8.141 | 1.035 |
| Red · Blue · Female | 7 | 8.859 | −1.035 |
| Red · Hazel · Male | 7 | 6.704 | 0.1766 |
| Red · Hazel · Female | 7 | 7.296 | −0.1766 |
| Red · Green · Male | 7 | 6.704 | 0.1766 |
| Red · Green · Female | 7 | 7.296 | −0.1766 |
| Blond · Brown · Male | 3 | 2.535 | 0.3758 |
| Blond · Brown · Female | 4 | 4.465 | −0.3758 |
| Blond · Blue · Male | 30 | 34.047 | −1.704 |
| Blond · Blue · Female | 64 | 59.953 | 1.704 |
| Blond · Hazel · Male | 5 | 3.622 | 0.9446 |
| Blond · Hazel · Female | 5 | 6.378 | −0.9446 |
| Blond · Green · Male | 8 | 5.795 | 1.227 |
| Blond · Green · Female | 8 | 10.205 | −1.227 |
- Model (generating class): [hair × eye] [hair × sex]. Every cell of the 4 × 4 × 2 table is fitted, empty cells included.
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
- Hair eye sex backwardhair_eye · factors: hair, eye, sex
- Ucb homogeneousucb_admissions · factors: admit, gender, dept
- Hair eye independencehair_eye · factors: hair, eye
- Vision counts backward stricts4_vision · factors: right eye, left eye
- Counts saturateds4_haireye_counts · count: students · factors: hair, eye, sex
- Counts backwards4_haireye_counts · count: students · factors: eye, sex, hair
- Degenerate single levelhair_eye · factors: hair, eye, sex
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- More than two groups, categorical: χ² independence, Fisher's exact · Statistics Guide · B — Compare groups
- Categorical–categorical: χ², Fisher, Cramér's V · Statistics Guide · C — Test association
- Stratified, repeated, multiway, survey · Statistics Guide · E — Compare proportions / frequencies
What you need
- Variablescategorical / boolean · 2–4 columns · 2–12 levels
- Two to four categorical variables that form the table.
- Count (frequency weight)numeric · 0–1 column
- For tabulated data: the number of subjects in each row's cell (leave empty when every row is one subject).
Choices you make
statistics
- Modeldefault backward
Which associations the log-linear model includes, or backward elimination from the saturated model.
- Backward elimination from the saturated model(default) — Starts from all terms and drops those that aren't needed; pick it to find the simplest fit.
- Homogeneous association (all two-way terms) — Keeps all two-way terms with no three-way term; tests whether associations hold across levels.
- Mutual independence (main effects only) — Keeps main effects only; tests whether all the variables are independent.
- Saturated (all terms) — Keeps every term and fits the table exactly; pick it to read the terms, not to test fit.
- Keep a term when p ≤default 0.05
In backward elimination, terms with p above this are dropped from the model.
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 expected counts
G² and X² are χ² approximations; most expected cell counts should be ≥ 5 and none near 0.
Independent observations
Each subject is counted in exactly one cell.
What it reports
- Tests: Goodness of fit of the log-linear model
- n
- How many independent units the analysis used; it sets precision and power.
- cells
- Number of cells in the full cross-classification of the factors: the product of their level counts, empty cells included.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- model_label
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- g2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- x2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- df
- How much independent information is left to estimate variability after fitting the model.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- p_x2
- How surprising your data would be if the null hypothesis were true, as a probability.
- aic
- A model score balancing fit against complexity; lower is better, and only differences matter.
- n_params
- How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.
- steps
- How many interaction terms backward elimination removed. 0 when nothing was dropped or a fixed model was fitted.
- min_expected
- The counts a contingency table would have if the variables were independent; χ² needs them not too small.
Per group, level or term: drop_g2[<term>], drop_df[<term>], drop_p[<term>], adj_resid[<cell>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses pandas, numpy, scipy, statsmodels, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines fit Poisson GLMs by IRLS to a deviance tolerance of 1e-14 (statsmodels GLM ↔ glm); the coding of the design differs (patsy vs model.matrix) but G², X², fitted counts and residuals do not depend on it. Leverages for adjusted residuals: hatvalues() in R, the same QR formula in Python.
The exact script CodeSplash ran for example “Hair eye sex backward” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Log-linear models for multiway tables
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.loglinear 1.0.1 · spec f2b921fb1c5375ef
# Dataset: hair_eye (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import itertools
import math
import warnings as pywarnings
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import stats
from scipy.special import gammaln
import codesplash as cs
from codesplash.stats import categorical_adv as cat # hierarchical designs, generator bookkeeping (twins of codesplashr)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/hair_eye.parquet", columns=["hair", "eye", "sex"])
n_input = len(df)
df["hair"] = pd.Categorical(df["hair"], categories=["Black", "Brown", "Red", "Blond"]) # stored level order
df["eye"] = pd.Categorical(df["eye"], categories=["Brown", "Blue", "Hazel", "Green"]) # stored level order
df["sex"] = pd.Categorical(df["sex"], categories=["Male", "Female"]) # stored level order
df = df.dropna(subset=["hair", "eye", "sex"]) # listwise deletion over the analysis columns
df["hair"] = df["hair"].cat.remove_unused_categories()
df["eye"] = df["eye"].cat.remove_unused_categories()
df["sex"] = df["sex"].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, ["hair", "eye", "sex"]) # infinite values stop the run (registry/errors.yaml)
# %% Cells of the cross-table (empty cells included)
factors = ["hair", "eye", "sex"]
k = len(factors)
levels = [[str(v) for v in df[f].cat.categories] for f in factors]
nlev = [len(lv) for lv in levels]
weight = np.ones(len(df))
for f, m in zip(factors, nlev): # a variable with one category has no association to model
if m < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=f, min=2, k=m)
codes = [df[f].cat.codes.to_numpy(dtype=np.int64) for f in factors]
grid = list(itertools.product(*[range(m) for m in nlev]))
cell_index = {g: i for i, g in enumerate(grid)}
y = np.zeros(len(grid))
for i, g in enumerate(zip(*codes)):
y[cell_index[g]] += weight[i]
cell_codes = [np.array([g[f] for g in grid]) for f in range(k)]
n = float(y.sum())
ncell = len(grid)
def fit(gens):
"""Poisson GLM of the cell counts on the hierarchical model with generators ``gens``."""
x = cat.loglinear_design(cell_codes, nlev, gens)
with pywarnings.catch_warnings():
pywarnings.simplefilter("ignore")
res = sm.GLM(y, x, family=sm.families.Poisson()).fit(tol=1e-14, maxiter=200)
mu = np.asarray(res.mu)
with np.errstate(divide="ignore", invalid="ignore"):
dev = float(2 * np.sum(np.where(y > 0, y * np.log(y / mu), 0.0) - (y - mu)))
rank = int(np.linalg.matrix_rank(x))
ll = float(np.sum(y * np.log(np.maximum(mu, 1e-300)) - mu - gammaln(y + 1)))
return {"x": x, "mu": mu, "dev": max(dev, 0.0), "df": ncell - rank, "rank": rank, "aic": -2 * ll + 2 * rank,
"x2": float(np.sum((y - mu) ** 2 / mu))}
def label(g):
return " × ".join(factors[f] for f in g)
def chi2_p(stat, dfree):
return float(stats.chi2.sf(stat, dfree)) if dfree > 0 else math.nan
# %% Model
model = "backward"
alpha_drop = 0.05
saturated = [tuple(range(k))]
gens = {"saturated": saturated, "independence": [(f,) for f in range(k)],
"homogeneous": [g for g in itertools.combinations(range(k), 2)] if k > 2 else saturated, "backward": saturated}[model]
gens = sorted(gens, key=lambda t: (-len(t), t))
cur = fit(gens)
path = []
if model == "backward":
while True:
cands = [g for g in gens if len(g) >= 2]
if not cands:
break
tests = []
for g in cands:
red = fit(cat.reduce_generator(gens, g))
tests.append((g, red["dev"] - cur["dev"], red["df"] - cur["df"], chi2_p(red["dev"] - cur["dev"], red["df"] - cur["df"]), red))
best = max(range(len(tests)), key=lambda i: (tests[i][3], -i))
g, g2d, dfd, pd_, red = tests[best]
if not pd_ > alpha_drop:
break
gens = cat.reduce_generator(gens, g)
cur = red
path.append({"step": len(path) + 1, "term": label(g), "g2": g2d, "df": dfd, "p": pd_})
# %% Likelihood-ratio tests of each interaction in the final model
drops = []
for g in gens:
if len(g) >= 2:
red = fit(cat.reduce_generator(gens, g))
drops.append({"term": label(g), "g2": red["dev"] - cur["dev"], "df": red["df"] - cur["df"],
"p": chi2_p(red["dev"] - cur["dev"], red["df"] - cur["df"])})
mu = cur["mu"]
h = cat.hat_poisson(cur["x"], mu)
with np.errstate(divide="ignore", invalid="ignore"):
# Saturated cells (leverage 1) fit exactly: their adjusted residual is 0.
adj = np.where((mu > 0) & (1 - h > 1e-8), (y - mu) / np.sqrt(mu * np.maximum(1 - h, 1e-300)), 0.0)
model_label = " ".join(f"[{label(g)}]" for g in gens)
p = chi2_p(cur["dev"], cur["df"])
# %% Assumptions
small = float(np.mean(mu < 5))
assumptions = [
{"key": "expected", "label": "Enough expected counts", "status": "pass" if small <= 0.2 and mu.min() >= 1 else "warn",
"detail": f"{small:.0%} of fitted cell counts are below 5 (smallest {mu.min():.2f})."},
{"key": "independence", "label": "Independent observations", "status": "info", "detail": "Each subject is counted in one cell."},
]
# %% Result
values = {"n": n, "cells": ncell, "k": k, "model_label": model_label, "g2": cur["dev"], "x2": cur["x2"], "df": cur["df"],
"p": p, "p_x2": chi2_p(cur["x2"], cur["df"]), "aic": cur["aic"], "n_params": cur["rank"], "steps": len(path),
"min_expected": float(mu.min())}
for d in drops:
values[f"drop_g2[{d['term']}]"] = d["g2"]
values[f"drop_df[{d['term']}]"] = d["df"]
values[f"drop_p[{d['term']}]"] = d["p"]
cell_labels = [" · ".join(levels[f][g[f]] for f in range(k)) for g in grid]
if ncell <= 300:
for lab, a in zip(cell_labels, adj):
values[f"adj_resid[{lab}]"] = float(a)
tables = [
{"key": "terms", "title": "Likelihood-ratio tests of the interactions in the final model",
"columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "g2", "label": "ΔG²", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "number", "format": "p"}],
"rows": drops},
{"key": "cells", "title": "Observed and fitted counts",
"columns": [{"key": "cell", "label": " · ".join(factors), "type": "string"}, {"key": "observed", "label": "Observed", "type": "number"},
{"key": "fitted", "label": "Fitted", "type": "number"}, {"key": "adj", "label": "Adjusted residual", "type": "number"}],
"rows": [{"cell": lab, "observed": float(o), "fitted": float(f), "adj": float(a)} for lab, o, f, a in zip(cell_labels, y, mu, adj)]},
]
if path:
tables.insert(0, {"key": "path", "title": "Backward elimination",
"columns": [{"key": "step", "label": "Step", "type": "integer"}, {"key": "term", "label": "Removed", "type": "string"},
{"key": "g2", "label": "ΔG²", "type": "number"}, {"key": "df", "label": "df", "type": "integer"},
{"key": "p", "label": "p", "type": "number", "format": "p"}],
"rows": path})
charts = []
if drops:
charts.append(cs.chart("terms", "cleveland-dot", "Likelihood-ratio χ² of each interaction",
{"category": cs.col("term", [d["term"] for d in drops]), "value": cs.col("ΔG²", [d["g2"] for d in drops])}))
if k == 2:
charts.append(cs.chart("residuals", "matrix-heatmap", "Adjusted residuals",
{"row": cs.col(factors[0], [levels[0][g[0]] for g in grid]), "col": cs.col(factors[1], [levels[1][g[1]] for g in grid]),
"value": cs.col("adjusted residual", [float(a) for a in adj])}, controls={"scale": "diverging"}))
cs.publish({
"method": "contingency.loglinear",
"methodVersion": "1.0.1",
"title": "Log-linear model",
"engine": cs.engine_info("pandas", "numpy", "scipy", "statsmodels"),
"n": int(n),
"summary": f"Log-linear model {model_label}: G²({cur['df']}) = {cur['dev']:.2f}, {cs.fmt_p(p)} (X² = {cur['x2']:.2f}, AIC = {cur['aic']:.1f}).",
"apa": f"G²({cur['df']}, N = {int(n)}) = {cur['dev']:.2f}, {cs.fmt_p(p)}",
"statistics": [
{"key": "g2", "label": "G² (likelihood ratio)", "value": cur["dev"]},
{"key": "x2", "label": "Pearson X²", "value": cur["x2"]},
{"key": "df", "label": "df", "value": cur["df"]},
{"key": "p", "label": "p (G²)", "value": p, "format": "p"},
{"key": "aic", "label": "AIC", "value": cur["aic"]},
],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Model (generating class): {model_label}. Every cell of the {' × '.join(str(m) for m in nlev)} table is fitted, empty cells included."],
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Hair eye sex backward” · R version 4.5.1 (2025-06-13)
# Log-linear models for multiway tables
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.loglinear 1.0.1 · spec f2b921fb1c5375ef
# Dataset: hair_eye (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_cat_reduce_generator, cs_cat_gen_formula (generator bookkeeping, twins of codesplash.stats)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hair_eye.parquet", col_select = c("hair", "eye", "sex")))
n_input <- nrow(df)
df[["hair"]] <- factor(df[["hair"]], levels = c("Black", "Brown", "Red", "Blond")) # stored level order
df[["eye"]] <- factor(df[["eye"]], levels = c("Brown", "Blue", "Hazel", "Green")) # stored level order
df[["sex"]] <- factor(df[["sex"]], levels = c("Male", "Female")) # stored level order
df <- df[stats::complete.cases(df[c("hair", "eye", "sex")]), , 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("hair", "eye", "sex")) # infinite values stop the run (registry/errors.yaml)
# %% Cells of the cross-table (empty cells included)
factors <- c("hair", "eye", "sex")
k <- length(factors)
df$.w <- 1
tab <- stats::xtabs(stats::as.formula(paste(".w ~", paste(sprintf("`%s`", factors), collapse = " + "))), data = df)
cells <- as.data.frame(tab, responseName = ".n", stringsAsFactors = TRUE) # every cell, empty ones included
names(cells) <- c(factors, ".n") # keep names with spaces as they are
nlev <- vapply(factors, function(f) nlevels(cells[[f]]), 0L)
for (i in seq_len(k)) { # a variable with one category has no association to model
if (nlev[[i]] < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = factors[i], min = 2, k = nlev[[i]])
}
n <- sum(cells$.n)
ncell <- nrow(cells)
fit_gens <- function(gens) {
f <- stats::as.formula(paste(".n ~", cs_cat_gen_formula(gens, factors)))
m <- suppressWarnings(stats::glm(f, family = stats::poisson(), data = cells, control = stats::glm.control(epsilon = 1e-14, maxit = 200)))
list(fit = m, mu = stats::fitted(m), dev = max(stats::deviance(m), 0), df = stats::df.residual(m), rank = m$rank,
aic = stats::AIC(m), x2 = sum(stats::residuals(m, type = "pearson")^2))
}
lab_of <- function(g) paste(factors[g], collapse = " × ")
chi2_p <- function(stat, dfree) if (dfree > 0) stats::pchisq(stat, dfree, lower.tail = FALSE) else NaN
# %% Model
model <- "backward"
alpha_drop <- 0.05
saturated <- list(seq_len(k))
gens <- switch(model,
saturated = saturated,
independence = as.list(seq_len(k)),
homogeneous = if (k > 2) utils::combn(k, 2, simplify = FALSE) else saturated,
backward = saturated
)
gens <- cs_cat_sort_generators(gens)
cur <- fit_gens(gens)
path <- list()
if (model == "backward") {
repeat {
cands <- Filter(function(g) length(g) >= 2, gens)
if (!length(cands)) break
tests <- lapply(cands, function(g) {
red <- fit_gens(cs_cat_reduce_generator(gens, g))
list(g = g, g2 = red$dev - cur$dev, df = red$df - cur$df, p = chi2_p(red$dev - cur$dev, red$df - cur$df), red = red)
})
best <- which.max(vapply(tests, function(t) t$p, 0)) # first of tied maxima
tt <- tests[[best]]
if (!(tt$p > alpha_drop)) break
gens <- cs_cat_reduce_generator(gens, tt$g)
cur <- tt$red
path[[length(path) + 1]] <- list(step = length(path) + 1L, term = lab_of(tt$g), g2 = tt$g2, df = tt$df, p = tt$p)
}
}
# %% Likelihood-ratio tests of each interaction in the final model
drops <- list()
for (g in gens) {
if (length(g) >= 2) {
red <- fit_gens(cs_cat_reduce_generator(gens, g))
drops[[length(drops) + 1]] <- list(term = lab_of(g), g2 = red$dev - cur$dev, df = red$df - cur$df, p = chi2_p(red$dev - cur$dev, red$df - cur$df))
}
}
mu <- as.numeric(cur$mu)
h <- stats::hatvalues(cur$fit)
y <- cells$.n
adj <- ifelse(mu > 0 & 1 - h > 1e-8, (y - mu) / sqrt(mu * pmax(1 - h, 1e-300)), 0) # saturated cells (leverage 1) fit exactly
model_label <- paste(vapply(gens, function(g) sprintf("[%s]", lab_of(g)), ""), collapse = " ")
p <- chi2_p(cur$dev, cur$df)
# %% Assumptions
small <- mean(mu < 5)
assumptions <- list(
list(key = "expected", label = "Enough expected counts", status = if (small <= 0.2 && min(mu) >= 1) "pass" else "warn",
detail = sprintf("%.0f%% of fitted cell counts are below 5 (smallest %.2f).", 100 * small, min(mu))),
list(key = "independence", label = "Independent observations", status = "info", detail = "Each subject is counted in one cell.")
)
# %% Result
values <- list(n = n, cells = ncell, k = k, model_label = model_label, g2 = cur$dev, x2 = cur$x2, df = cur$df,
p = p, p_x2 = chi2_p(cur$x2, cur$df), aic = cur$aic, n_params = cur$rank, steps = length(path), min_expected = min(mu))
for (d in drops) {
values[[sprintf("drop_g2[%s]", d$term)]] <- d$g2
values[[sprintf("drop_df[%s]", d$term)]] <- d$df
values[[sprintf("drop_p[%s]", d$term)]] <- d$p
}
cell_labels <- apply(cells[factors], 1, function(r) paste(trimws(r), collapse = " · "))
if (ncell <= 300) for (i in seq_len(ncell)) values[[sprintf("adj_resid[%s]", cell_labels[i])]] <- adj[i]
tables <- list(
list(key = "terms", title = "Likelihood-ratio tests of the interactions in the final model",
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "g2", label = "ΔG²", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "number", format = "p")),
rows = drops),
list(key = "cells", title = "Observed and fitted counts",
columns = list(list(key = "cell", label = paste(factors, collapse = " · "), type = "string"), list(key = "observed", label = "Observed", type = "number"),
list(key = "fitted", label = "Fitted", type = "number"), list(key = "adj", label = "Adjusted residual", type = "number")),
rows = lapply(seq_len(ncell), function(i) list(cell = cell_labels[i], observed = y[i], fitted = mu[i], adj = adj[i])))
)
if (length(path)) {
tables <- c(list(list(key = "path", title = "Backward elimination",
columns = list(list(key = "step", label = "Step", type = "integer"), list(key = "term", label = "Removed", type = "string"),
list(key = "g2", label = "ΔG²", type = "number"), list(key = "df", label = "df", type = "integer"),
list(key = "p", label = "p", type = "number", format = "p")),
rows = path)), tables)
}
charts <- list()
if (length(drops)) {
charts[[length(charts) + 1]] <- cs_chart("terms", "cleveland-dot", "Likelihood-ratio χ² of each interaction",
list(category = cs_col("term", vapply(drops, function(d) d$term, "")), value = cs_col("ΔG²", vapply(drops, function(d) d$g2, 0))))
}
if (k == 2) {
charts[[length(charts) + 1]] <- cs_chart("residuals", "matrix-heatmap", "Adjusted residuals",
list(row = cs_col(factors[1], as.character(cells[[factors[1]]])), col = cs_col(factors[2], as.character(cells[[factors[2]]])),
value = cs_col("adjusted residual", adj)), controls = list(scale = "diverging"))
}
cs_publish(list(
method = "contingency.loglinear",
methodVersion = "1.0.1",
title = "Log-linear model",
engine = cs_engine_info("stats", "nanoparquet"),
n = as.integer(n),
summary = sprintf("Log-linear model %s: G²(%d) = %.2f, %s (X² = %.2f, AIC = %.1f).", model_label, as.integer(cur$df), cur$dev, cs_fmt_p(p), cur$x2, cur$aic),
apa = sprintf("G²(%d, N = %d) = %.2f, %s", as.integer(cur$df), as.integer(n), cur$dev, cs_fmt_p(p)),
statistics = list(
list(key = "g2", label = "G² (likelihood ratio)", value = cur$dev),
list(key = "x2", label = "Pearson X²", value = cur$x2),
list(key = "df", label = "df", value = cur$df),
list(key = "p", label = "p (G²)", value = p, format = "p"),
list(key = "aic", label = "AIC", value = cur$aic)
),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Model (generating class): %s. Every cell of the %s table is fitted, empty cells included.", model_label, paste(nlev, collapse = " × "))),
charts = charts,
values = values
))
Sources
- Bishop, Y. M. M., Fienberg, S. E., & Holland, P. W. (1975). Discrete Multivariate Analysis. MIT Press.
- Agresti, A. (2002). Categorical Data Analysis (2nd ed.), ch. 8–9. Wiley.
From the CodeSplash method registry · contingency.loglinear v1.0.1.