DRegression models · regression.compare_nonnested
Compare non-nested models (J, Cox, encompassing, PE, Vuong)
Which of two rival regression models explains the outcome better, when neither contains the other?
Two linear models with different predictors for the same outcome: the Davidson–MacKinnon J test, Pesaran's Cox test and the encompassing F test ask whether each model is rejected in the direction of the other; Vuong's and Clarke's tests ask which one is closer to the truth. Or a linear model against a log-linear one with the PE test.
A real result
Example “Rival proxies”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
J test of A: t(146) = 1.36, p = .177; J test of B: t(146) = 10.45, p < .001
- J t (H₀: A)
- 1.356
- J t (H₀: B)
- 10.451
- Vuong z
- 5.025
Assumptions
- Non-nested models — Each model has predictors the other lacks.
- Classical errors — The tests assume normal, constant-variance, independent errors under the null model; check the chosen model's residuals in Linear regression.
Is each model rejected in the direction of the other?
| Test | Statistic (H₀: A) | p (A) | Statistic (H₀: B) | p (B) |
|---|---|---|---|---|
| J test, t(146) | 1.356 | .177 | 10.451 | < .001 |
| Cox test (Pesaran), z | −1.517 | .129 | −21.391 | < .001 |
| Encompassing, F(·, 145) | 0.9255 | .399 | 54.243 | < .001 |
A small p rejects that model: the rival's predictors carry information it misses. Both rejected: neither model is adequate; neither rejected: the data cannot tell them apart.
Which model is closer to the truth?
| Test | Statistic | p | Favors |
|---|---|---|---|
| Vuong z | 5.025 | < .001 | A |
| Clarke (rows where A fits better, of 150) | 120 | < .001 | A |
Correction: none. Both tests compare pointwise log-likelihoods; Clarke's sign test is robust to heavy tails.
- Model A: a1, a2; Model B: b1, b2; both with an intercept, fitted to the same 150 rows.
J test of A: t(146) = 1.36, p = .177; J test of B: t(146) = 10.45, p < .001
- J t (H₀: A)
- 1.356
- J t (H₀: B)
- 10.451
- Vuong z
- 5.025
Assumptions
- Non-nested models — Each model has predictors the other lacks.
- Classical errors — The tests assume normal, constant-variance, independent errors under the null model; check the chosen model's residuals in Linear regression.
Is each model rejected in the direction of the other?
| Test | Statistic (H₀: A) | p (A) | Statistic (H₀: B) | p (B) |
|---|---|---|---|---|
| J test, t(146) | 1.356 | .177 | 10.451 | < .001 |
| Cox test (Pesaran), z | −1.517 | .129 | −21.391 | < .001 |
| Encompassing, F(·, 145) | 0.9255 | .399 | 54.243 | < .001 |
A small p rejects that model: the rival's predictors carry information it misses. Both rejected: neither model is adequate; neither rejected: the data cannot tell them apart.
Which model is closer to the truth?
| Test | Statistic | p | Favors |
|---|---|---|---|
| Vuong z | 5.025 | < .001 | A |
| Clarke (rows where A fits better, of 150) | 120 | < .001 | A |
Correction: none. Both tests compare pointwise log-likelihoods; Clarke's sign test is robust to heavy tails.
- Model A: a1, a2; Model B: b1, b2; both with an intercept, fitted to the same 150 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
- Rival proxiesreg_nonnested · model_a: a1, a2 · model_b: b1, b2 · outcome: y
- Rival bicreg_nonnested · model_a: a1, a2, b2 · model_b: b1 · outcome: y
- Linear vs logreg_nonnested · model_a: a1, a2 · model_b: a1, a2 · outcome: y
- Rival mtcarsmtcars · model_a: weight (1000 lbs), cyl_f · model_b: hp, qsec · outcome: mpg
- Degenerate constantreg_nonnested · model_a: a1, a2 · model_b: b1, b2 · outcome: y
- Degenerate n3reg_nonnested · model_a: a1, a2 · model_b: b1, b2 · outcome: y
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 · 1 column
- The numeric variable you are analyzing.
- Model A predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
- The first model's predictors (with an intercept). For the PE test, Model A is the linear model of the outcome.
- Model B predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
- The rival model's predictors. For the PE test, Model B is the linear model of log(outcome); it may use the same predictors as A.
Choices you make
hypothesis
- Comparisondefault rival
Compare two rival sets of predictors, or a linear model with a log-linear model of the same outcome.
- Two rival models of the outcome(default) — J, Cox and encompassing tests in both directions, plus Vuong and Clarke.
- Linear (A) against log-linear (B) — MacKinnon–White–Davidson PE test: y on Model A against log(y) on Model B (the outcome must be positive).
statistics
- Vuong / Clarke correctiondefault none
Without a correction the model with more predictors has an edge; AIC or BIC charges for the difference in coefficients.
- None(default) — Uses the raw Vuong statistic; pick it when the models have the same number of coefficients.
- AIC (penalize extra coefficients) — Penalizes the larger model as AIC does; the common choice when models differ in size.
- BIC (heavier penalty) — Penalizes extra coefficients more as the sample grows; favors the smaller 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.
Non-nested models
Neither model's predictors span the other's; otherwise compare them as nested models.
Classical errors
Normal, constant-variance, independent errors in the true model (the tests' t, F and normal references rely on them).
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- k_a
- How many coefficients the model estimated, counting the intercept.
- k_b
- How many coefficients the model estimated, counting the intercept.
- comparison
- Which comparison ran: rival (two rival predictor sets, tested both ways) or log_linear (linear against log-linear, PE test).
- preferred
- Compares two models' row-by-row log-likelihoods, without assuming either is true. A positive z favors the first.
Per group, level or term: r2_a, r2_b, aic_a, aic_b, bic_a, bic_b, j_a_t, j_a_p, j_b_t, j_b_p, cox_a_z, cox_a_p, cox_b_z, cox_b_p, enc_a_f, enc_a_p, enc_b_f, enc_b_p, enc_df2, vuong_z, vuong_p, vuong_lr, clarke_b, clarke_p, pe_lin_t, pe_lin_p, pe_log_t, pe_log_p
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; they reproduce lmtest's jtest, coxtest (z with a two-sided normal p), encomptest and petest, and statsmodels' compare_j / compare_cox / compare_encompassing.
The exact script CodeSplash ran for example “Rival proxies” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare non-nested models (J, Cox, encompassing, PE, Vuong)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.compare_nonnested 1.0.1 · spec 7cf4ce0bf4055bdd
# Dataset: reg_nonnested (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
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/reg_nonnested.parquet", columns=["y", "a1", "a2", "b1", "b2"])
n_input = len(df)
df = df.dropna(subset=["y", "a1", "a2", "b1", "b2"]) # 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, ["y", "a1", "a2", "b1", "b2"]) # infinite values stop the run (registry/errors.yaml)
# %% Two designs on the same rows
y = "y"
model_a = ["a1", "a2"]
model_b = ["b1", "b2"]
comparison = "rival" # rival | log_linear
correction = "none" # none | aic | bic
yv = df[y].to_numpy(dtype=float)
XA = csreg.design_matrix(df, model_a, "none").to_numpy()
XB = csreg.design_matrix(df, model_b, "none").to_numpy()
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
# More rows than the coefficients of the largest test regression: the J and PE tests add one
# column to a model, and the encompassing model holds the columns of both.
both = list(dict.fromkeys(model_a + model_b))
k_test = max(XA.shape[1], XB.shape[1]) + 1
if comparison == "rival":
k_test = max(k_test, csreg.design_matrix(df, both, "none").shape[1])
cs.check_rows(len(df), k_test + 1, "Comparing non-nested models")
for col in [y] + both:
check_not_constant(df[col], col) # one value (or one level with data) is no variation
for X in (XA, XB):
if np.linalg.matrix_rank(X) < X.shape[1]:
cs.cs_error("CS_E_COLLINEAR")
n = len(yv)
values = {"n": n, "k_a": XA.shape[1], "k_b": XB.shape[1], "comparison": comparison}
tables = []
alpha = 0.05
if comparison == "rival":
_, ka, kept_b = mc.union_columns(XA, XB)
_, kb, kept_a = mc.union_columns(XB, XA)
if kept_b == 0 or kept_a == 0:
inner = "B" if kept_b == 0 else "A"
cs.cs_error("CS_E_UNDEFINED", what="A non-nested comparison",
reason=f"Model {inner} is nested in the other model (its predictors add nothing); compare them with Compare nested models instead")
j = mc.j_test(XA, XB, yv)
cx = mc.cox_test(XA, XB, yv)
en = mc.encompassing(XA, XB, yv)
vc = mc.vuong_clarke(XA, XB, yv, correction)
rss_a, rss_b = float(((yv - XA @ np.linalg.lstsq(XA, yv, rcond=None)[0]) ** 2).sum()), float(((yv - XB @ np.linalg.lstsq(XB, yv, rcond=None)[0]) ** 2).sum())
tss = float(((yv - yv.mean()) ** 2).sum())
ll_a, ll_b = mc.gaussian_loglik(rss_a, n), mc.gaussian_loglik(rss_b, n)
values.update({"r2_a": 1 - rss_a / tss, "r2_b": 1 - rss_b / tss,
"aic_a": -2 * ll_a + 2 * (XA.shape[1] + 1), "aic_b": -2 * ll_b + 2 * (XB.shape[1] + 1),
"bic_a": -2 * ll_a + math.log(n) * (XA.shape[1] + 1), "bic_b": -2 * ll_b + math.log(n) * (XB.shape[1] + 1),
"j_a_t": j["a_t"], "j_a_p": j["a_p"], "j_b_t": j["b_t"], "j_b_p": j["b_p"],
"cox_a_z": cx["a_z"], "cox_a_p": cx["a_p"], "cox_b_z": cx["b_z"], "cox_b_p": cx["b_p"],
"enc_a_f": en["a_f"], "enc_a_p": en["a_p"], "enc_b_f": en["b_f"], "enc_b_p": en["b_p"], "enc_df2": en["df2"],
"vuong_z": vc["z"], "vuong_p": vc["p"], "vuong_lr": vc["lr"], "clarke_b": vc["clarke_b"], "clarke_p": vc["clarke_p"]})
rej_a, rej_b = j["a_p"] < alpha, j["b_p"] < alpha
preferred = "B" if rej_a and not rej_b else "A" if rej_b and not rej_a else "neither" if rej_a and rej_b else "both"
tables.append({"key": "direction", "title": "Is each model rejected in the direction of the other?", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "of_a", "label": "Statistic (H₀: A)", "type": "number"},
{"key": "p_a", "label": "p (A)", "type": "pvalue"}, {"key": "of_b", "label": "Statistic (H₀: B)", "type": "number"},
{"key": "p_b", "label": "p (B)", "type": "pvalue"}], "rows": [
{"test": f"J test, t({j['a_df']})", "of_a": j["a_t"], "p_a": j["a_p"], "of_b": j["b_t"], "p_b": j["b_p"]},
{"test": "Cox test (Pesaran), z", "of_a": cx["a_z"], "p_a": cx["a_p"], "of_b": cx["b_z"], "p_b": cx["b_p"]},
{"test": f"Encompassing, F(·, {en['df2']})", "of_a": en["a_f"], "p_a": en["a_p"], "of_b": en["b_f"], "p_b": en["b_p"]}],
"note": "A small p rejects that model: the rival's predictors carry information it misses. Both rejected: neither model is adequate; neither rejected: the data cannot tell them apart."})
tables.append({"key": "closeness", "title": "Which model is closer to the truth?", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "favours", "label": "Favors", "type": "string"}], "rows": [
{"test": "Vuong z", "statistic": vc["z"], "p": vc["p"], "favours": "A" if vc["z"] > 0 else "B"},
{"test": f"Clarke (rows where A fits better, of {n})", "statistic": float(vc["clarke_b"]), "p": vc["clarke_p"], "favours": "A" if vc["clarke_b"] > n / 2 else "B"}],
"note": f"Correction: {correction}. Both tests compare pointwise log-likelihoods; Clarke's sign test is robust to heavy tails."})
summary = (f"J test: Model A is {'rejected' if rej_a else 'not rejected'} ({cs.fmt_p(j['a_p'])}), Model B is {'rejected' if rej_b else 'not rejected'} ({cs.fmt_p(j['b_p'])}); "
f"Vuong z = {vc['z']:.2f} ({cs.fmt_p(vc['p'])}, positive favors A).")
apa = f"J test of A: t({j['a_df']}) = {cs.fmt_num(j['a_t'])}, {cs.fmt_p(j['a_p'])}; J test of B: t({j['b_df']}) = {cs.fmt_num(j['b_t'])}, {cs.fmt_p(j['b_p'])}"
else:
pe = mc.pe_test(XA, XB, yv)
values.update({"pe_lin_t": pe["lin_t"], "pe_lin_p": pe["lin_p"], "pe_log_t": pe["log_t"], "pe_log_p": pe["log_p"]})
rej_lin, rej_log = pe["lin_p"] < alpha, pe["log_p"] < alpha
preferred = "log-linear" if rej_lin and not rej_log else "linear" if rej_log and not rej_lin else "neither" if rej_lin and rej_log else "both"
tables.append({"key": "pe", "title": "PE test: linear against log-linear", "columns": [
{"key": "test", "label": "H₀", "type": "string"}, {"key": "t", "label": "t", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"}], "rows": [
{"test": f"Linear: {y} on Model A", "t": pe["lin_t"], "df": pe["lin_df"], "p": pe["lin_p"]},
{"test": f"Log-linear: log({y}) on Model B", "t": pe["log_t"], "df": pe["log_df"], "p": pe["log_p"]}],
"note": "A small p rejects that functional form in favor of the other."})
summary = (f"PE test: the linear model is {'rejected' if rej_lin else 'not rejected'} ({cs.fmt_p(pe['lin_p'])}) and the log-linear model is "
f"{'rejected' if rej_log else 'not rejected'} ({cs.fmt_p(pe['log_p'])}).")
apa = f"PE test of the linear model: t({pe['lin_df']}) = {cs.fmt_num(pe['lin_t'])}, {cs.fmt_p(pe['lin_p'])}"
values["preferred"] = preferred
# %% Assumptions
assumptions = [
{"key": "non_nested", "label": "Non-nested models", "status": "pass",
"detail": "Each model has predictors the other lacks." if comparison == "rival" else "The PE test compares two functional forms (y and log y), which are non-nested even with the same predictors."},
{"key": "classical_errors", "label": "Classical errors", "status": "info",
"detail": "The tests assume normal, constant-variance, independent errors under the null model; check the chosen model's residuals in Linear regression."},
]
cs.publish({
"method": "regression.compare_nonnested",
"methodVersion": "1.0.1",
"title": "Compare non-nested models",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": apa,
"statistics": ([{"key": "j_a_t", "label": "J t (H₀: A)", "value": values["j_a_t"]}, {"key": "j_b_t", "label": "J t (H₀: B)", "value": values["j_b_t"]},
{"key": "vuong_z", "label": "Vuong z", "value": values["vuong_z"]}] if comparison == "rival" else
[{"key": "pe_lin_t", "label": "PE t (linear)", "value": values["pe_lin_t"]}, {"key": "pe_log_t", "label": "PE t (log-linear)", "value": values["pe_log_t"]}]),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Model A: {', '.join(model_a)}; Model B: {', '.join(model_b)}; both with an intercept, fitted to the same {n} rows."],
"charts": [],
"values": values,
})
The exact script CodeSplash ran for example “Rival proxies” · R version 4.5.1 (2025-06-13)
# Compare non-nested models (J, Cox, encompassing, PE, Vuong)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.compare_nonnested 1.0.1 · spec 7cf4ce0bf4055bdd
# Dataset: reg_nonnested (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/reg_nonnested.parquet", col_select = c("y", "a1", "a2", "b1", "b2")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("y", "a1", "a2", "b1", "b2")]), , 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("y", "a1", "a2", "b1", "b2")) # infinite values stop the run (registry/errors.yaml)
# %% Two designs on the same rows
y <- "y"
model_a <- c("a1", "a2")
model_b <- c("b1", "b2")
comparison <- "rival" # rival | log_linear
correction <- "none" # none | aic | bic
yv <- as.numeric(df[[y]])
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
# More rows than the coefficients of the largest test regression: the J and PE tests add one
# column to a model, and the encompassing model holds the columns of both.
both <- union(model_a, model_b)
k_test <- max(length(cs_design_labels(df, model_a)), length(cs_design_labels(df, model_b))) + 1
if (comparison == "rival") k_test <- max(k_test, length(cs_design_labels(df, both)))
cs_check_rows(nrow(df), k_test + 1, "Comparing non-nested models")
for (col in c(y, both)) cs_check_not_constant(df[[col]], col) # one value (or one level with data) is no variation
XA <- unname(model.matrix(cs_model_formula(y, model_a, "none"), data = df))
XB <- unname(model.matrix(cs_model_formula(y, model_b, "none"), data = df))
if (qr(XA)$rank < ncol(XA) || qr(XB)$rank < ncol(XB)) cs_error("CS_E_COLLINEAR")
n <- length(yv)
values <- list(n = n, k_a = ncol(XA), k_b = ncol(XB), comparison = comparison)
tables <- list()
alpha <- 0.05
fmt_t <- function(x) cs_fmt_num(x)
if (comparison == "rival") {
kept_b <- cs_union_columns(XA, XB)$kept
kept_a <- cs_union_columns(XB, XA)$kept
if (kept_b == 0 || kept_a == 0) {
cs_error("CS_E_UNDEFINED", what = "A non-nested comparison",
reason = sprintf("Model %s is nested in the other model (its predictors add nothing); compare them with Compare nested models instead", if (kept_b == 0) "B" else "A"))
}
j <- cs_j_test(XA, XB, yv)
cx <- cs_cox_test(XA, XB, yv)
en <- cs_encompassing(XA, XB, yv)
vc <- cs_vuong_clarke(XA, XB, yv, correction)
rss_a <- sum(qr.resid(qr(XA), yv)^2)
rss_b <- sum(qr.resid(qr(XB), yv)^2)
tss <- sum((yv - mean(yv))^2)
ll_a <- cs_gaussian_loglik(rss_a, n)
ll_b <- cs_gaussian_loglik(rss_b, n)
values <- c(values, list(r2_a = 1 - rss_a / tss, r2_b = 1 - rss_b / tss,
aic_a = -2 * ll_a + 2 * (ncol(XA) + 1), aic_b = -2 * ll_b + 2 * (ncol(XB) + 1),
bic_a = -2 * ll_a + log(n) * (ncol(XA) + 1), bic_b = -2 * ll_b + log(n) * (ncol(XB) + 1),
j_a_t = j$a_t, j_a_p = j$a_p, j_b_t = j$b_t, j_b_p = j$b_p,
cox_a_z = cx$a_z, cox_a_p = cx$a_p, cox_b_z = cx$b_z, cox_b_p = cx$b_p,
enc_a_f = en$a_f, enc_a_p = en$a_p, enc_b_f = en$b_f, enc_b_p = en$b_p, enc_df2 = en$df2,
vuong_z = vc$z, vuong_p = vc$p, vuong_lr = vc$lr, clarke_b = vc$clarke_b, clarke_p = vc$clarke_p))
rej_a <- j$a_p < alpha
rej_b <- j$b_p < alpha
preferred <- if (rej_a && !rej_b) "B" else if (rej_b && !rej_a) "A" else if (rej_a && rej_b) "neither" else "both"
tables[[1]] <- list(key = "direction", title = "Is each model rejected in the direction of the other?", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "of_a", label = "Statistic (H₀: A)", type = "number"),
list(key = "p_a", label = "p (A)", type = "pvalue"), list(key = "of_b", label = "Statistic (H₀: B)", type = "number"),
list(key = "p_b", label = "p (B)", type = "pvalue")), rows = list(
list(test = sprintf("J test, t(%d)", as.integer(j$a_df)), of_a = j$a_t, p_a = j$a_p, of_b = j$b_t, p_b = j$b_p),
list(test = "Cox test (Pesaran), z", of_a = cx$a_z, p_a = cx$a_p, of_b = cx$b_z, p_b = cx$b_p),
list(test = sprintf("Encompassing, F(·, %d)", as.integer(en$df2)), of_a = en$a_f, p_a = en$a_p, of_b = en$b_f, p_b = en$b_p)),
note = "A small p rejects that model: the rival's predictors carry information it misses. Both rejected: neither model is adequate; neither rejected: the data cannot tell them apart.")
tables[[2]] <- list(key = "closeness", title = "Which model is closer to the truth?", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
list(key = "p", label = "p", type = "pvalue"), list(key = "favours", label = "Favors", type = "string")), rows = list(
list(test = "Vuong z", statistic = vc$z, p = vc$p, favours = if (vc$z > 0) "A" else "B"),
list(test = sprintf("Clarke (rows where A fits better, of %d)", as.integer(n)), statistic = as.numeric(vc$clarke_b), p = vc$clarke_p,
favours = if (vc$clarke_b > n / 2) "A" else "B")),
note = sprintf("Correction: %s. Both tests compare pointwise log-likelihoods; Clarke's sign test is robust to heavy tails.", correction))
summary <- sprintf("J test: Model A is %s (%s), Model B is %s (%s); Vuong z = %.2f (%s, positive favors A).",
if (rej_a) "rejected" else "not rejected", cs_fmt_p(j$a_p), if (rej_b) "rejected" else "not rejected", cs_fmt_p(j$b_p),
vc$z, cs_fmt_p(vc$p))
apa <- sprintf("J test of A: t(%d) = %s, %s; J test of B: t(%d) = %s, %s", as.integer(j$a_df), fmt_t(j$a_t), cs_fmt_p(j$a_p),
as.integer(j$b_df), fmt_t(j$b_t), cs_fmt_p(j$b_p))
statistics <- list(list(key = "j_a_t", label = "J t (H₀: A)", value = j$a_t), list(key = "j_b_t", label = "J t (H₀: B)", value = j$b_t),
list(key = "vuong_z", label = "Vuong z", value = vc$z))
} else {
pe <- cs_pe_test(XA, XB, yv)
values <- c(values, list(pe_lin_t = pe$lin_t, pe_lin_p = pe$lin_p, pe_log_t = pe$log_t, pe_log_p = pe$log_p))
rej_lin <- pe$lin_p < alpha
rej_log <- pe$log_p < alpha
preferred <- if (rej_lin && !rej_log) "log-linear" else if (rej_log && !rej_lin) "linear" else if (rej_lin && rej_log) "neither" else "both"
tables[[1]] <- list(key = "pe", title = "PE test: linear against log-linear", columns = list(
list(key = "test", label = "H₀", type = "string"), list(key = "t", label = "t", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")), rows = list(
list(test = sprintf("Linear: %s on Model A", y), t = pe$lin_t, df = pe$lin_df, p = pe$lin_p),
list(test = sprintf("Log-linear: log(%s) on Model B", y), t = pe$log_t, df = pe$log_df, p = pe$log_p)),
note = "A small p rejects that functional form in favor of the other.")
summary <- sprintf("PE test: the linear model is %s (%s) and the log-linear model is %s (%s).",
if (rej_lin) "rejected" else "not rejected", cs_fmt_p(pe$lin_p), if (rej_log) "rejected" else "not rejected", cs_fmt_p(pe$log_p))
apa <- sprintf("PE test of the linear model: t(%d) = %s, %s", as.integer(pe$lin_df), fmt_t(pe$lin_t), cs_fmt_p(pe$lin_p))
statistics <- list(list(key = "pe_lin_t", label = "PE t (linear)", value = pe$lin_t), list(key = "pe_log_t", label = "PE t (log-linear)", value = pe$log_t))
}
values$preferred <- preferred
# %% Assumptions
assumptions <- list(
list(key = "non_nested", label = "Non-nested models", status = "pass",
detail = if (comparison == "rival") "Each model has predictors the other lacks." else "The PE test compares two functional forms (y and log y), which are non-nested even with the same predictors."),
list(key = "classical_errors", label = "Classical errors", status = "info",
detail = "The tests assume normal, constant-variance, independent errors under the null model; check the chosen model's residuals in Linear regression.")
)
cs_publish(list(
method = "regression.compare_nonnested",
methodVersion = "1.0.1",
title = "Compare non-nested models",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = apa,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Model A: %s; Model B: %s; both with an intercept, fitted to the same %d rows.", paste(model_a, collapse = ", "), paste(model_b, collapse = ", "), as.integer(n))),
charts = list(),
values = values
))
Sources
- Davidson, R., & MacKinnon, J. G. (1981). Several tests for model specification in the presence of alternative hypotheses. Econometrica, 49, 781–793.
- Pesaran, M. H. (1974). On the general problem of model selection. Review of Economic Studies, 41, 153–171.
- Mizon, G. E., & Richard, J.-F. (1986). The encompassing principle and its application to testing non-nested hypotheses. Econometrica, 54, 657–678.
- MacKinnon, J. G., White, H., & Davidson, R. (1983). Tests for model specification in the presence of alternative hypotheses: Some further results. Journal of Econometrics, 21, 53–70.
- Vuong, Q. H. (1989). Likelihood ratio tests for model selection and non-nested hypotheses. Econometrica, 57, 307–333.
- Clarke, K. A. (2007). A simple distribution-free test for nonnested model selection. Political Analysis, 15, 347–363.
From the CodeSplash method registry · regression.compare_nonnested v1.0.1.