DRegression models · regression.compare_nested
Compare nested models (LR, Wald, score, partial F)
Do the added predictors improve the model significantly?
Fits a base model and a full model that adds predictors, then tests the added terms with the likelihood-ratio, Wald and score (Lagrange multiplier) tests — and the partial F test for linear models — alongside AIC and BIC. Linear (Gaussian), logistic (binomial) and Poisson models.
A real result
Example “Linear two added”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
LR χ²(2) = 28.10, p < .001
- LR χ²
- 28.096
- p (LR)
- < .001
- Wald χ²
- 39.370
- Score χ²
- 18.700
- Δ AIC
- −24.096
Plots
View data
| Model | p | LR χ²(2) | AIC |
|---|---|---|---|
| Base (2 coefficients) | — | — | 181.24 |
| Full (4 coefficients) | 7.926e-7 | 28.096 | 157.14 |
Assumptions
- Nested models — The full model adds weight (1000 lbs), qsec (2 column(s)) to the base predictors hp; both use the same 32 rows.
- Large-sample χ² reference — The partial F test is exact under normal errors; the LR, Wald and score χ² versions are its large-sample forms (they bracket each other: Wald ≥ LR ≥ score).
Tests of the added terms
| Test | Statistic | Reference | p |
|---|---|---|---|
| Likelihood ratio | 28.096 | χ²(2) | < .001 |
| Wald | 39.370 | χ²(2) | < .001 |
| Score (Lagrange multiplier) | 18.700 | χ²(2) | < .001 |
| Partial F (extra sum of squares) | 19.685 | F(2, 28) | < .001 |
H₀: the 2 added coefficient(s) are all zero.
Model fit
| Model | Coefficients | Log-likelihood | AIC | BIC |
|---|---|---|---|---|
| Base | 2 | −87.619 | 181.24 | 185.64 |
| Full | 4 | −73.571 | 157.14 | 164.47 |
Lower AIC / BIC is better.
Added coefficients (full model)
| Term | Estimate | SE | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| weight (1000 lbs) | −4.359 | 0.7527 | −5.791 | < .001 | −5.901 | −2.817 |
| qsec | 0.5108 | 0.4392 | 1.163 | .255 | −0.3889 | 1.411 |
- Linear models fitted to the same 32 rows.
LR χ²(2) = 28.10, p < .001
- LR χ²
- 28.096
- p (LR)
- < .001
- Wald χ²
- 39.370
- Score χ²
- 18.700
- Δ AIC
- −24.096
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Nested models — The full model adds weight (1000 lbs), qsec (2 column(s)) to the base predictors hp; both use the same 32 rows.
- Large-sample χ² reference — The partial F test is exact under normal errors; the LR, Wald and score χ² versions are its large-sample forms (they bracket each other: Wald ≥ LR ≥ score).
Tests of the added terms
| Test | Statistic | Reference | p |
|---|---|---|---|
| Likelihood ratio | 28.096 | χ²(2) | < .001 |
| Wald | 39.370 | χ²(2) | < .001 |
| Score (Lagrange multiplier) | 18.700 | χ²(2) | < .001 |
| Partial F (extra sum of squares) | 19.685 | F(2, 28) | < .001 |
H₀: the 2 added coefficient(s) are all zero.
Model fit
| Model | Coefficients | Log-likelihood | AIC | BIC |
|---|---|---|---|---|
| Base | 2 | −87.619 | 181.24 | 185.64 |
| Full | 4 | −73.571 | 157.14 | 164.47 |
Lower AIC / BIC is better.
Added coefficients (full model)
| Term | Estimate | SE | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| weight (1000 lbs) | −4.359 | 0.7527 | −5.791 | < .001 | −5.901 | −2.817 |
| qsec | 0.5108 | 0.4392 | 1.163 | .255 | −0.3889 | 1.411 |
- Linear models fitted to the same 32 rows.
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
- Linear two addedmtcars · added: weight (1000 lbs), qsec · outcome: mpg · predictors: hp
- Linear factor addediris · added: Species · outcome: Sepal.Length · predictors: Petal.Length
- Intercept only basemtcars · added: hp · outcome: mpg
- Logistic birthwtbirthwt · added: smoke, ht · outcome: low · predictors: age, mother weight (lb)
- Poisson warpbreakswarpbreaks · added: tension · outcome: breaks · predictors: wool
- Degenerate constantmtcars · added: weight (1000 lbs), qsec · outcome: mpg · predictors: hp
- Degenerate n3mtcars · added: weight (1000 lbs), qsec · outcome: mpg · predictors: hp
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Continuous outcome: linear regression · Statistics Guide · D — Predict an outcome
- Post-estimation: robust SEs, marginal effects, contrasts · Statistics Guide · D — Predict an outcome
What you need
- Outcomenumeric / categorical / boolean · 1 column
- Numeric for a linear or Poisson model; two levels (or 0/1) for a logistic model.
- Base model predictorsnumeric / categorical / boolean · 0–20 columns · 2–30 levels
- Predictors in both models. Leave empty to compare against the intercept-only model.
- Predictors to testnumeric / categorical / boolean · 1–10 columns · 2–30 levels
- Predictors only the full model has; the tests ask whether they improve on the base model together.
Choices you make
hypothesis
- Modeldefault gaussian
The model type both nested models share: linear, logistic or Poisson.
- Linear (numeric outcome)(default) — Ordinary least squares; adds the partial F test, which is exact under normal errors.
- Logistic (two outcome levels) — Logit link; LR = drop in deviance.
- Poisson (counts) — Log link for non-negative counts; LR = drop in deviance.
- Event (modeled level)default —
The outcome level whose probability is modeled; default: the second level (true for yes/no columns).
- 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.
Nested models
Every base-model term is also in the full model, and both use the same rows.
Large-sample χ² reference
The LR, Wald and score tests are asymptotic; the partial F test is exact for linear models with normal errors.
What it reports
- Tests: Added terms (likelihood ratio)
- n
- How many independent units the analysis used; it sets precision and power.
- q
- Effect size for the difference between two correlations — the difference of their Fisher z values.
- k_reduced
- How many coefficients the model estimated, counting the intercept.
- k_full
- How many coefficients the model estimated, counting the intercept.
- family
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- lr
- Compares nested models by how much the log-likelihood improves when parameters are added.
- lr_p
- Compares nested models by how much the log-likelihood improves when parameters are added.
- wald
- Tests a parameter by dividing its estimate by its standard error; quick, but unreliable near boundaries or with separation.
- wald_p
- Tests a parameter by dividing its estimate by its standard error; quick, but unreliable near boundaries or with separation.
- score
- Lagrange multiplier χ² for adding the extra terms, computed from the base model alone. Larger means stronger evidence.
- score_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- loglik_reduced
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- loglik_full
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- aic_reduced
- A model score balancing fit against complexity; lower is better, and only differences matter.
- aic_full
- A model score balancing fit against complexity; lower is better, and only differences matter.
- bic_reduced
- Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
- bic_full
- Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
- delta_aic
- How far a model's AIC is above the best model's; the scale for comparing candidates.
- delta_bic
- Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
Per group, level or term: f, f_df1, f_df2, f_p, r2_reduced, r2_full, delta_r2, f2_partial, rss_reduced, rss_full, deviance_reduced, deviance_full, n_events, event_level, coef[<term>], se[…], stat[…], p[…], ci_low[…], ci_high[…]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines use the codesplash twins: least squares by QR / lstsq, and GLMs by IRLS run to a relative deviance change below 1e-14 (tighter than statsmodels' and R glm's defaults).
- Score test for GLMs: U'I⁻¹U at the converged base model (= statsmodels' score_test); R's anova(test = "Rao") takes one working-weights step and can differ in the fifth digit for Poisson models.
- The Wald χ² uses the full model's classical covariance (s² = RSS/(n − k)), as statsmodels' wald_test and lmtest::waldtest do; textbook treatments with the ML variance give a larger value.
The exact script CodeSplash ran for example “Linear two added” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare nested models (LR, Wald, score, partial F)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.compare_nested 1.0.2 · spec ed2a671d84f24d12
# Dataset: mtcars (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_not_constant
from codesplash.stats import modelcomp as mc
from codesplash.stats import regression as csreg
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["mpg", "hp", "weight (1000 lbs)", "qsec"])
n_input = len(df)
df = df.dropna(subset=["mpg", "hp", "weight (1000 lbs)", "qsec"]) # listwise deletion over the analysis columns
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, ["mpg", "hp", "weight (1000 lbs)", "qsec"]) # infinite values stop the run (registry/errors.yaml)
# %% Outcome and the two designs (same rows; the full design starts with the base columns)
outcome = "mpg"
predictors = ["hp"]
added = ["weight (1000 lbs)", "qsec"]
family = "gaussian" # gaussian | binomial | poisson
conf = 0.95
overlap = sorted(set(predictors) & set(added))
if overlap:
raise ValueError(f"{', '.join(overlap)} cannot be both a base predictor and a predictor to test.")
event = None
if family == "binomial":
if isinstance(df[outcome].dtype, pd.CategoricalDtype):
levels_y = [str(x) for x in df[outcome].cat.categories]
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
if event not in levels_y:
cs.cs_error("CS_E_NOT_A_LEVEL", level=event, column=outcome)
yv = (df[outcome].astype(str) == event).to_numpy(dtype=float)
else:
yv = df[outcome].to_numpy(dtype=float)
if not np.all(np.isin(yv, [0.0, 1.0])):
raise ValueError(f"A logistic model needs a two-level outcome or 0/1 values; {outcome} has other values.")
else:
if isinstance(df[outcome].dtype, pd.CategoricalDtype):
raise ValueError(f"{outcome} is categorical: choose the logistic model, or a numeric outcome.")
yv = df[outcome].to_numpy(dtype=float)
if family == "poisson" and (np.any(yv < 0) or np.any(yv != np.round(yv))):
raise ValueError(f"A Poisson model needs non-negative whole counts; {outcome} has other values.")
X_full = csreg.design_matrix(df, predictors + added, "none")
X_base = csreg.design_matrix(df, predictors, "none") if predictors else pd.DataFrame({"(Intercept)": np.ones(len(df))}, index=df.index)
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
cs.check_rows(len(df), X_full.shape[1] + 1, "Comparing nested models") # more rows than coefficients of the full model
for col in [outcome] + predictors + added:
check_not_constant(df[col], col) # one value (or one level with data) is no variation
if np.linalg.matrix_rank(X_full.to_numpy()) < X_full.shape[1]:
cs.cs_error("CS_E_COLLINEAR")
terms = list(X_full.columns)
added_terms = terms[X_base.shape[1]:]
# %% Tests
res = mc.nested(X_base.to_numpy(), X_full.to_numpy(), yv, family)
n, q = res["n"], res["q"]
coef, cov = res["coef"], res["cov"]
se = np.sqrt(np.diag(cov))
dfree = n - X_full.shape[1]
rows = []
values = {}
for j, term in enumerate(terms):
if term not in added_terms:
continue
st = coef[j] / se[j]
if family == "gaussian":
p = float(2 * stats.t.sf(abs(st), dfree))
crit = stats.t.ppf(1 - (1 - conf) / 2, dfree)
else:
p = float(2 * stats.norm.sf(abs(st)))
crit = stats.norm.ppf(1 - (1 - conf) / 2)
row = {"term": term, "estimate": float(coef[j]), "se": float(se[j]), "stat": float(st), "p": p,
"ci_low": float(coef[j] - crit * se[j]), "ci_high": float(coef[j] + crit * se[j])}
rows.append(row)
values.update({f"{key}[{term}]": row[key2] for key, key2 in
(("coef", "estimate"), ("se", "se"), ("stat", "stat"), ("p", "p"), ("ci_low", "ci_low"), ("ci_high", "ci_high"))})
# %% Assumptions
assumptions = [
{"key": "nested", "label": "Nested models", "status": "pass",
"detail": f"The full model adds {', '.join(added)} ({q} column(s)) to {('the base predictors ' + ', '.join(predictors)) if predictors else 'the intercept-only model'}; both use the same {n} rows."},
]
if family == "gaussian":
assumptions.append({"key": "large_sample", "label": "Large-sample χ² reference", "status": "info",
"detail": "The partial F test is exact under normal errors; the LR, Wald and score χ² versions are its large-sample forms (they bracket each other: Wald ≥ LR ≥ score)."})
else:
small = min(yv.sum(), n - yv.sum()) if family == "binomial" else yv.sum()
assumptions.append({"key": "large_sample", "label": "Large-sample χ² reference", "status": "warn" if small < 10 * res["k_full"] else "pass",
"detail": ("Few events for the number of coefficients: the χ² approximations can be poor; prefer the likelihood ratio test." if small < 10 * res["k_full"]
else "Enough events for the χ² approximations; the likelihood ratio test is usually the most reliable of the three.")})
# %% Result
family_label = {"gaussian": "linear", "binomial": "logistic", "poisson": "Poisson"}[family]
values.update({k: res[k] for k in ("n", "q", "k_reduced", "k_full", "lr", "lr_p", "wald", "wald_p", "score", "score_p", "loglik_reduced",
"loglik_full", "aic_reduced", "aic_full", "bic_reduced", "bic_full", "delta_aic", "delta_bic")})
values["family"] = family
if family == "gaussian":
values.update({k: res[k] for k in ("f", "f_df1", "f_df2", "f_p", "r2_reduced", "r2_full", "delta_r2", "f2_partial", "rss_reduced", "rss_full")})
else:
values.update({"deviance_reduced": res["deviance_reduced"], "deviance_full": res["deviance_full"]})
if family == "binomial":
values["n_events"] = int(yv.sum())
if event is not None:
values["event_level"] = event
test_rows = [
{"test": "Likelihood ratio", "statistic": res["lr"], "reference": f"χ²({q})", "p": res["lr_p"]},
{"test": "Wald", "statistic": res["wald"], "reference": f"χ²({q})", "p": res["wald_p"]},
{"test": "Score (Lagrange multiplier)", "statistic": res["score"], "reference": f"χ²({q})", "p": res["score_p"]},
]
if family == "gaussian":
test_rows.append({"test": "Partial F (extra sum of squares)", "statistic": res["f"], "reference": f"F({q}, {res['f_df2']})", "p": res["f_p"]})
fit_rows = [
{"model": "Base", "k": res["k_reduced"], "log_lik": res["loglik_reduced"], "aic": res["aic_reduced"], "bic": res["bic_reduced"]},
{"model": "Full", "k": res["k_full"], "log_lik": res["loglik_full"], "aic": res["aic_full"], "bic": res["bic_full"]},
]
alpha = 0.05
sig = res["lr_p"] < alpha
pct = f"{conf:.0%}"
stat_label = "t" if family == "gaussian" else "z"
cs.publish({
"method": "regression.compare_nested",
"methodVersion": "1.0.2",
"title": "Compare nested models",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": (f"Adding {', '.join(added)} to the {family_label} model {'improves it significantly' if sig else 'does not improve it significantly'} "
f"(likelihood ratio χ²({q}) = {res['lr']:.2f}, {cs.fmt_p(res['lr_p'])}); AIC changes by {res['delta_aic']:.2f}."),
"apa": f"LR χ²({q}) = {cs.fmt_num(res['lr'])}, {cs.fmt_p(res['lr_p'])}",
"statistics": [
{"key": "lr", "label": "LR χ²", "value": res["lr"]}, {"key": "lr_p", "label": "p (LR)", "value": res["lr_p"], "format": "p"},
{"key": "wald", "label": "Wald χ²", "value": res["wald"]}, {"key": "score", "label": "Score χ²", "value": res["score"]},
{"key": "delta_aic", "label": "Δ AIC", "value": res["delta_aic"]},
],
"tables": [
{"key": "tests", "title": "Tests of the added terms", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
{"key": "reference", "label": "Reference", "type": "string"}, {"key": "p", "label": "p", "type": "pvalue"}],
"rows": test_rows, "note": f"H₀: the {q} added coefficient(s) are all zero."},
{"key": "fit", "title": "Model fit", "columns": [
{"key": "model", "label": "Model", "type": "string"}, {"key": "k", "label": "Coefficients", "type": "integer"},
{"key": "log_lik", "label": "Log-likelihood", "type": "number"}, {"key": "aic", "label": "AIC", "type": "number"},
{"key": "bic", "label": "BIC", "type": "number"}], "rows": fit_rows, "note": "Lower AIC / BIC is better."},
{"key": "added", "title": "Added coefficients (full model)", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "stat", "label": stat_label, "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "ci_low", "label": f"{pct} CI low", "type": "number"},
{"key": "ci_high", "label": f"{pct} CI high", "type": "number"}], "rows": rows},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"{family_label.capitalize()} models fitted to the same {n} rows" + (f"; event: {outcome} = {event}" if event else "") + "."],
# The two models as a ladder (Chart Lab `nested-compare`): AIC of each, the LR test of the full against the base.
"charts": [cs.chart(
"nested", "nested-compare", "Base and full model: AIC and the likelihood ratio test",
{"model": cs.col("Model", [f"Base ({res['k_reduced']} coefficients)", f"Full ({res['k_full']} coefficients)"],
levels=[f"Base ({res['k_reduced']} coefficients)", f"Full ({res['k_full']} coefficients)"]),
"value": cs.col("AIC", [res["aic_reduced"], res["aic_full"]], kind="numeric"),
"statistic": cs.col(f"LR χ²({q})", [None, res["lr"]], kind="numeric"),
"p": cs.col("p", [None, res["lr_p"]], kind="numeric")},
)],
"values": values,
})
The exact script CodeSplash ran for example “Linear two added” · R version 4.5.1 (2025-06-13)
# Compare nested models (LR, Wald, score, partial F)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.compare_nested 1.0.2 · spec ed2a671d84f24d12
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = c("mpg", "hp", "weight (1000 lbs)", "qsec")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("mpg", "hp", "weight (1000 lbs)", "qsec")]), , 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("mpg", "hp", "weight (1000 lbs)", "qsec")) # infinite values stop the run (registry/errors.yaml)
# %% Outcome and the two designs (same rows; the full design starts with the base columns)
outcome <- "mpg"
predictors <- c("hp")
added <- c("weight (1000 lbs)", "qsec")
family <- "gaussian" # gaussian | binomial | poisson
conf <- 0.95
overlap <- sort(intersect(predictors, added))
if (length(overlap)) stop(sprintf("%s cannot be both a base predictor and a predictor to test.", paste(overlap, collapse = ", ")))
event <- NULL
if (family == "binomial") {
if (is.factor(df[[outcome]])) {
levels_y <- levels(df[[outcome]])
if (length(levels_y) != 2) cs_error("CS_E_GROUP_COUNT", column = outcome, expected = 2, k = length(levels_y))
event <- levels_y[2] # default: the second stored level
if (!(event %in% levels_y)) cs_error("CS_E_NOT_A_LEVEL", level = event, column = outcome)
yv <- as.numeric(as.character(df[[outcome]]) == event)
} else {
yv <- as.numeric(df[[outcome]])
if (!all(yv %in% c(0, 1))) stop(sprintf("A logistic model needs a two-level outcome or 0/1 values; %s has other values.", outcome))
}
} else {
if (is.factor(df[[outcome]])) stop(sprintf("%s is categorical: choose the logistic model, or a numeric outcome.", outcome))
yv <- as.numeric(df[[outcome]])
if (family == "poisson" && (any(yv < 0) || any(yv != round(yv)))) stop(sprintf("A Poisson model needs non-negative whole counts; %s has other values.", outcome))
}
terms <- cs_design_labels(df, c(predictors, added), "none")
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_rows(nrow(df), length(terms) + 1, "Comparing nested models") # more rows than coefficients of the full model
for (col in c(outcome, predictors, added)) cs_check_not_constant(df[[col]], col) # one value (or one level with data) is no variation
X_full <- model.matrix(cs_model_formula(outcome, c(predictors, added), "none"), data = df)
colnames(X_full) <- terms
X_base <- if (length(predictors)) model.matrix(cs_model_formula(outcome, predictors, "none"), data = df) else matrix(1, nrow(df), 1)
if (qr(X_full)$rank < ncol(X_full)) cs_error("CS_E_COLLINEAR")
added_terms <- terms[(ncol(X_base) + 1):length(terms)]
# %% Tests
res <- cs_nested_tests(X_base, X_full, yv, family)
n <- res$n
q <- res$q
se <- sqrt(diag(res$cov))
dfree <- n - ncol(X_full)
rows <- list()
values <- list()
for (j in seq_along(terms)) {
term <- terms[j]
if (!(term %in% added_terms)) next
st <- res$coef[j] / se[j]
if (family == "gaussian") {
p <- 2 * pt(abs(st), dfree, lower.tail = FALSE)
crit <- qt(1 - (1 - conf) / 2, dfree)
} else {
p <- 2 * pnorm(abs(st), lower.tail = FALSE)
crit <- qnorm(1 - (1 - conf) / 2)
}
row <- list(term = term, estimate = res$coef[j], se = se[j], stat = st, p = p, ci_low = res$coef[j] - crit * se[j], ci_high = res$coef[j] + crit * se[j])
rows[[length(rows) + 1]] <- row
for (pair in list(c("coef", "estimate"), c("se", "se"), c("stat", "stat"), c("p", "p"), c("ci_low", "ci_low"), c("ci_high", "ci_high"))) {
values[[sprintf("%s[%s]", pair[1], term)]] <- row[[pair[2]]]
}
}
# %% Assumptions
assumptions <- list(list(key = "nested", label = "Nested models", status = "pass",
detail = sprintf("The full model adds %s (%d column(s)) to %s; both use the same %d rows.", paste(added, collapse = ", "), as.integer(q),
if (length(predictors)) paste("the base predictors", paste(predictors, collapse = ", ")) else "the intercept-only model", as.integer(n))))
if (family == "gaussian") {
assumptions[[2]] <- list(key = "large_sample", label = "Large-sample χ² reference", status = "info",
detail = "The partial F test is exact under normal errors; the LR, Wald and score χ² versions are its large-sample forms (they bracket each other: Wald ≥ LR ≥ score).")
} else {
small <- if (family == "binomial") min(sum(yv), n - sum(yv)) else sum(yv)
few <- small < 10 * res$k_full
assumptions[[2]] <- list(key = "large_sample", label = "Large-sample χ² reference", status = if (few) "warn" else "pass",
detail = if (few) "Few events for the number of coefficients: the χ² approximations can be poor; prefer the likelihood ratio test."
else "Enough events for the χ² approximations; the likelihood ratio test is usually the most reliable of the three.")
}
# %% Result
family_label <- switch(family, gaussian = "linear", binomial = "logistic", poisson = "Poisson")
for (k in c("n", "q", "k_reduced", "k_full", "lr", "lr_p", "wald", "wald_p", "score", "score_p", "loglik_reduced", "loglik_full",
"aic_reduced", "aic_full", "bic_reduced", "bic_full", "delta_aic", "delta_bic")) values[[k]] <- res[[k]]
values$family <- family
if (family == "gaussian") {
for (k in c("f", "f_df1", "f_df2", "f_p", "r2_reduced", "r2_full", "delta_r2", "f2_partial", "rss_reduced", "rss_full")) values[[k]] <- res[[k]]
} else {
values$deviance_reduced <- res$deviance_reduced
values$deviance_full <- res$deviance_full
}
if (family == "binomial") {
values$n_events <- as.integer(sum(yv))
if (!is.null(event)) values$event_level <- event
}
test_rows <- list(
list(test = "Likelihood ratio", statistic = res$lr, reference = sprintf("χ²(%d)", as.integer(q)), p = res$lr_p),
list(test = "Wald", statistic = res$wald, reference = sprintf("χ²(%d)", as.integer(q)), p = res$wald_p),
list(test = "Score (Lagrange multiplier)", statistic = res$score, reference = sprintf("χ²(%d)", as.integer(q)), p = res$score_p)
)
if (family == "gaussian") {
test_rows[[4]] <- list(test = "Partial F (extra sum of squares)", statistic = res$f, reference = sprintf("F(%d, %d)", as.integer(q), as.integer(res$f_df2)), p = res$f_p)
}
fit_rows <- list(
list(model = "Base", k = res$k_reduced, log_lik = res$loglik_reduced, aic = res$aic_reduced, bic = res$bic_reduced),
list(model = "Full", k = res$k_full, log_lik = res$loglik_full, aic = res$aic_full, bic = res$bic_full)
)
sig <- res$lr_p < 0.05
pct <- sprintf("%.0f%%", conf * 100)
cs_publish(list(
method = "regression.compare_nested",
methodVersion = "1.0.2",
title = "Compare nested models",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = sprintf("Adding %s to the %s model %s (likelihood ratio χ²(%d) = %.2f, %s); AIC changes by %.2f.", paste(added, collapse = ", "), family_label,
if (sig) "improves it significantly" else "does not improve it significantly", as.integer(q), res$lr, cs_fmt_p(res$lr_p), res$delta_aic),
apa = sprintf("LR χ²(%d) = %s, %s", as.integer(q), cs_fmt_num(res$lr), cs_fmt_p(res$lr_p)),
statistics = list(
list(key = "lr", label = "LR χ²", value = res$lr), list(key = "lr_p", label = "p (LR)", value = res$lr_p, format = "p"),
list(key = "wald", label = "Wald χ²", value = res$wald), list(key = "score", label = "Score χ²", value = res$score),
list(key = "delta_aic", label = "Δ AIC", value = res$delta_aic)
),
tables = list(
list(key = "tests", title = "Tests of the added terms", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
list(key = "reference", label = "Reference", type = "string"), list(key = "p", label = "p", type = "pvalue")),
rows = test_rows, note = sprintf("H₀: the %d added coefficient(s) are all zero.", as.integer(q))),
list(key = "fit", title = "Model fit", columns = list(
list(key = "model", label = "Model", type = "string"), list(key = "k", label = "Coefficients", type = "integer"),
list(key = "log_lik", label = "Log-likelihood", type = "number"), list(key = "aic", label = "AIC", type = "number"),
list(key = "bic", label = "BIC", type = "number")), rows = fit_rows, note = "Lower AIC / BIC is better."),
list(key = "added", title = "Added coefficients (full model)", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "stat", label = if (family == "gaussian") "t" else "z", type = "number"),
list(key = "p", label = "p", type = "pvalue"), list(key = "ci_low", label = paste(pct, "CI low"), type = "number"),
list(key = "ci_high", label = paste(pct, "CI high"), type = "number")), rows = rows)
),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(toupper(substr(family_label, 1, 1)), substring(family_label, 2), sprintf(" models fitted to the same %d rows", as.integer(n)),
if (!is.null(event)) sprintf("; event: %s = %s", outcome, event) else "", ".")),
# The two models as a ladder (Chart Lab `nested-compare`): AIC of each, the LR test of the full against the base.
charts = list(cs_chart(
"nested", "nested-compare", "Base and full model: AIC and the likelihood ratio test",
list(model = cs_col("Model", sprintf(c("Base (%d coefficients)", "Full (%d coefficients)"), c(res$k_reduced, res$k_full)),
levels = sprintf(c("Base (%d coefficients)", "Full (%d coefficients)"), c(res$k_reduced, res$k_full))),
value = cs_col("AIC", c(res$aic_reduced, res$aic_full), kind = "numeric"),
statistic = cs_col(sprintf("LR \u03c7\u00b2(%d)", q), c(NA, res$lr), kind = "numeric"),
p = cs_col("p", c(NA, res$lr_p), kind = "numeric"))
)),
values = values
))
Sources
- Buse, A. (1982). The likelihood ratio, Wald, and Lagrange multiplier tests: An expository note. The American Statistician, 36, 153–157.
- Rao, C. R. (1948). Large sample tests of statistical hypotheses concerning several parameters. Proc. Cambridge Philosophical Society, 44, 50–57.
- Engle, R. F. (1984). Wald, likelihood ratio, and Lagrange multiplier tests in econometrics. Handbook of Econometrics, 2, 775–826.
- Fox, J. (2016). Applied Regression Analysis and Generalized Linear Models (3rd ed.), ch. 6 and 15. Sage.
From the CodeSplash method registry · regression.compare_nested v1.0.2.