Skip to content

Rival models: J, Cox, encompassing, PE and Vuong tests

When neither model contains the other, an F test can't choose. These tests pit rival models against each other, and sometimes reject both.

Advanced ~12 min11 steps

What runs in CodeSplash

You will be able to

  • Recognize when two models are non-nested
  • Run and read the J, Cox and encompassing tests in both directions
  • Use the PE test to choose between a linear and a log-linear outcome
  • Interpret Vuong's test, and the case where both models are rejected

Read first

01

Two explanations, no shared structure

Read

Does income predict spending better, or does wealth? Each model has terms the other lacks, so neither is a special case of the other. A partial FF test needs nesting, so it can't help.

AIC can rank the two, but it gives no sense of how sure you should be. Non-nested tests add that. Most of them run in both directions, and that's the key to reading them.

02

The J test

Read

The Davidson–MacKinnon J testDavidson–MacKinnon J testAdds one model's fitted values to its rival. If they help, the rival is missing something. Run it in both directions. asks: if model A is right, should model B's predictions add anything?

Fit B, take its fitted values, and add them to A. If their coefficient is non-zero, A is missing something B knows.

Then swap and repeat. That gives four possible outcomes:

  • A survives, B rejected: prefer A.
  • B survives, A rejected: prefer B.
  • Both rejected: neither is adequate. Perhaps combine them.
  • Neither rejected: the data can't separate them.
03

Make a prediction

Predict

Predict first

Model A uses a1 and a2, and fits with R2R^2 of 0.55. Model B uses b1 and b2, with R2R^2 of 0.23. What do you expect from the two J tests?

A survives, B rejectedB survives, A rejectedBoth rejectedNeither rejected
Reveal

Adding B's fit to A gives p = .177: A is not rejected. Adding A's fit to B gives p < .001: B is rejected. So the data favor A, as the card's A shows.

04

Cox and encompassing

Read

Cox's testCox testCompares the likelihood a model achieves with what it would predict if its rival were true. It's for non-nested models. compares the log-likelihood you see under one model with what that model would predict about the other. It has good properties but relies on normal errors.

The encompassing testEncompassing testFits a model containing both rivals' terms, then F tests whether each set of terms can be dropped. fits a large model containing both sets of terms, then tests whether either set can be dropped. It's an FF test, and it's a clean way to ask, "does A already explain what B explains?"

For the same models, Cox gives p = .129 for A and p < .001 for B; encompassing gives p = .399 and p < .001.

05

When tests disagree

Reflect

On mtcars, weight and cylinders (A) against horsepower and quarter-mile time (B): J gives p = .091 for A. Cox gives p = .035. On these 32 cars the tests give somewhat different verdicts on A, and all of them firmly reject B.

So read the pattern, not a single threshold. Here the evidence favors A, with a hint that it could be improved. How would you word that in a report, without calling either model true?

06

Vuong

Read

Vuong's test doesn't assume either model is true. It compares their row-by-row log-likelihoods and asks whether one fits reliably closer to the data. A positive zz favors A.

For the rival proxies, zz = 5.03, p < .001. Clarke's sign test uses the same row-by-row comparison and needs fewer assumptions.

07

Linear or log outcome?

Predict

When yy and log⁡y\log y are the rival outcomes, you can't compare R2R^2 or AIC directly: they're on different scales. The PE testPE testChooses between a linear and a log-linear outcome by adding a term for how far each model's prediction is from the other's. (MacKinnon, White and Davidson) adds a term measuring how far each model's prediction is from the other's.

Predict first

In these simulated data, the predictors' effects multiply rather than add. Which form should the test reject?

The linear formThe log formNeither
Reveal

The linear form: it gives p = .026, and the log form gives p = .973. The card names log-linear.

08

Read the card

In the app
Compare non-nested modelsRecorded · Python and R agreeRecorded 2026-11-17 · 29 values compared
R

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?

TestStatistic (H₀: A)p (A)Statistic (H₀: B)p (B)
J test, t(146)1.356.17710.451< .001
Cox test (Pesaran), z−1.517.129−21.391< .001
Encompassing, F(·, 145)0.9255.39954.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?

TestStatisticpFavors
Vuong z5.025< .001A
Clarke (rows where A fits better, of 150)120< .001A

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.
The exact R script · R 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
))
Python

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?

TestStatistic (H₀: A)p (A)Statistic (H₀: B)p (B)
J test, t(146)1.356.17710.451< .001
Cox test (Pesaran), z−1.517.129−21.391< .001
Encompassing, F(·, 145)0.9255.39954.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?

TestStatisticpFavors
Vuong z5.025< .001A
Clarke (rows where A fits better, of 150)120< .001A

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.
The exact Python script · Python 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,
})

Check both directions of each test before reading the summary.

09

Check your understanding

Checkpoint

Check yourself

Both J tests reject. What does it suggest?

Show the answer

Answer: b

Each model adds to the other. Consider a model with terms from both, if the subject matter supports it.

Check yourself

Neither J test rejects. What does it suggest?

Show the answer

Answer: a

A lack of rejection isn't evidence for either. With overlapping predictors or few rows, these tests have little power.

Check yourself

Why can't you compare R² between y ~ x and log(y) ~ x?

Show the answer

Answer: b

R² is a share of variance in the outcome you fit. The PE test compares the two forms directly.

Check yourself

The J test, Cox's test and the encompassing test all report two results. Why two?

Show the answer

Answer: a

"A survives, B rejected" is a different finding from "both rejected" or "neither rejected", and one direction alone can't tell them apart.

Check yourself

What does Cox's test rely on?

Show the answer

Answer: a

It compares the log-likelihood you see under one model with what that model predicts about the other, and that calculation assumes normal errors.

Check yourself

On the card above, Cox's test of model A gives p = .129, and Cox's test of model B gives p < .001. What does that say?

Show the answer

Answer: a

Each p-value tests the model it names. A survives. That doesn't prove A is right: it's only better supported than this rival.

Check yourself

What does the encompassing test fit?

Show the answer

Answer: a

If B's terms can be dropped from the joint model, then A already explains what B explains.

Check yourself

The encompassing test of A gives p = .399, and the test of B gives p < .001. Which reading fits?

Show the answer

Answer: a

B's terms can be dropped without a clear loss, and A's can't. It agrees with the J test here, as it often does.

Check yourself

A PE test gives p = .026 against the linear form, and p = .973 against the log form. Which form does it favor?

Show the answer

Answer: a

The linear form is rejected and the log form isn't. Check it against the residual plots too, because the log also changes what a coefficient means.

Check yourself

When do you reach for the PE test rather than the J test?

Show the answer

Answer: a

The J test compares rival predictors for one outcome. The PE test compares two forms of the outcome, where R² can't be compared.

10

Pit two models against each other

In the app

Give the outcome, then the terms of model A and model B. Set comparison to the linear-versus-log form to run the PE test.

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

df = pd.read_csv("mtcars.csv")
df["fit_b"] = smf.ols("mpg ~ hp + qsec", data=df).fit().fittedvalues
df["fit_a"] = smf.ols("mpg ~ wt + C(cyl)", data=df).fit().fittedvalues
print("J for A:", smf.ols("mpg ~ wt + C(cyl) + fit_b", data=df).fit().pvalues["fit_b"])
print("J for B:", smf.ols("mpg ~ hp + qsec + fit_a", data=df).fit().pvalues["fit_a"])
R
df <- read.csv("mtcars.csv")
a <- lm(mpg ~ wt + factor(cyl), data = df)
b <- lm(mpg ~ hp + qsec, data = df)
df$fit_b <- fitted(b)
df$fit_a <- fitted(a)
summary(lm(mpg ~ wt + factor(cyl) + fit_b, data = df))$coefficients["fit_b", ]
summary(lm(mpg ~ hp + qsec + fit_a, data = df))$coefficients["fit_a", ]
11

Recap

Recap
  • Non-nested models need their own tests, run in both directions.
  • Four outcomes: prefer A, prefer B, reject both, or can't tell.
  • Vuong's test doesn't assume either model is true.
  • Use the PE test for linear versus log-linear outcomes, since R2R^2 can't compare them.

Concepts in this lesson