DRegression models · regression.quantile
Quantile regression
How do predictors shift a chosen quantile (the median, the 90th percentile …) of a numeric outcome?
Linear quantile regression (Koenker–Bassett): coefficients for the τ-th conditional quantile with Hendricks–Koenker (nid) or Powell kernel sandwich standard errors, the Wald test of all slopes, Koenker–Machado pseudo-R¹, a check that the solution is unique, and the quantile process across τ = 0.1 … 0.9 with a check for crossing quantile curves. Robust to outliers in the outcome and makes no assumption about the error distribution; slopes that differ across τ reveal heteroscedasticity or effects on spread and shape, not just location.
A real result
Example “Median heteroscedastic”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
pseudo-R¹ = 0.520, Wald F(3, 297) = 218.66, p < .001
- Wald F
- 218.66
- p
- < .001
- Pseudo-R¹
- 0.5204
Plots
View data
| B | high | Term | low |
|---|---|---|---|
| 0.3386 | 0.3652 | income | 0.3120 |
| 0.5571 | 1.431 | area: suburban | −0.3163 |
| 2.440 | 3.505 | area: urban | 1.375 |
View data
| Term | τ | B |
|---|---|---|
| income | 0.1000 | 0.2694 |
| area: suburban | 0.1000 | 1.735 |
| area: urban | 0.1000 | 3.437 |
| income | 0.2500 | 0.2841 |
| area: suburban | 0.2500 | 1.528 |
| area: urban | 0.2500 | 2.934 |
| income | 0.5000 | 0.3386 |
| area: suburban | 0.5000 | 0.5571 |
| area: urban | 0.5000 | 2.440 |
| income | 0.7500 | 0.3877 |
| area: suburban | 0.7500 | 1.062 |
| area: urban | 0.7500 | 4.205 |
| income | 0.9000 | 0.4058 |
| area: suburban | 0.9000 | 1.387 |
| area: urban | 0.9000 | 3.884 |
Assumptions
- Unique solution — The optimal coefficients are unique.
- Local density estimates — All 301 local density estimates are positive (bandwidth h = 0.1450).
- Non-crossing quantiles — Fitted quantiles increase with τ for every row.
- Linear conditional quantile — No assumption about the error distribution; the τ-th quantile of the outcome is assumed linear in the predictors, with independent rows.
Coefficients for the 0.5 quantile
| Term | B | SE | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| (Intercept) | 4.288 | 0.4119 | 10.411 | < .001 | 3.478 | 5.099 |
| income | 0.3386 | 0.0135 | 25.064 | < .001 | 0.3120 | 0.3652 |
| area: suburban | 0.5571 | 0.4438 | 1.255 | .210 | −0.3163 | 1.431 |
| area: urban | 2.440 | 0.5410 | 4.510 | < .001 | 1.375 | 3.505 |
Each slope is the change in the 0.5 quantile of spending per unit of the predictor (or versus the reference level).
Quantile process
| τ | Term | B | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| 0.1000 | (Intercept) | 1.912 | 0.6723 | 0.5891 | 3.235 |
| 0.1000 | income | 0.2694 | 0.0190 | 0.2319 | 0.3069 |
| 0.1000 | area: suburban | 1.735 | 0.7356 | 0.2876 | 3.183 |
| 0.1000 | area: urban | 3.437 | 0.7361 | 1.988 | 4.886 |
| 0.2500 | (Intercept) | 3.422 | 0.7086 | 2.027 | 4.816 |
| 0.2500 | income | 0.2841 | 0.0125 | 0.2596 | 0.3086 |
| 0.2500 | area: suburban | 1.528 | 0.6710 | 0.2071 | 2.848 |
| 0.2500 | area: urban | 2.934 | 0.7255 | 1.506 | 4.362 |
| 0.5000 | (Intercept) | 4.288 | 0.4119 | 3.478 | 5.099 |
| 0.5000 | income | 0.3386 | 0.0135 | 0.3120 | 0.3652 |
| 0.5000 | area: suburban | 0.5571 | 0.4438 | −0.3163 | 1.431 |
| 0.5000 | area: urban | 2.440 | 0.5410 | 1.375 | 3.505 |
| 0.7500 | (Intercept) | 4.117 | 0.5852 | 2.965 | 5.268 |
| 0.7500 | income | 0.3877 | 0.0154 | 0.3574 | 0.4179 |
| 0.7500 | area: suburban | 1.062 | 0.5917 | −0.1022 | 2.227 |
| 0.7500 | area: urban | 4.205 | 0.6380 | 2.950 | 5.461 |
| 0.9000 | (Intercept) | 5.336 | 0.8480 | 3.667 | 7.005 |
| 0.9000 | income | 0.4058 | 0.0166 | 0.3732 | 0.4385 |
| 0.9000 | area: suburban | 1.387 | 0.8519 | −0.2892 | 3.064 |
| 0.9000 | area: urban | 3.884 | 0.7886 | 2.332 | 5.436 |
Slopes that change with τ mean the predictor affects the spread or shape of the outcome, not only its location.
- Linear program solved exactly (quantreg Barrodale–Roberts, refit at the vertex); Hendricks–Koenker (nid) sandwich standard errors with t tests on n − k = 297 df.
- Pseudo-R¹ (Koenker–Machado) is 1 − check loss of the model / check loss of the intercept-only quantile.
pseudo-R¹ = 0.520, Wald F(3, 297) = 218.66, p < .001
- Wald F
- 218.66
- p
- < .001
- Pseudo-R¹
- 0.5204
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Unique solution — The optimal coefficients are unique.
- Local density estimates — All 301 local density estimates are positive (bandwidth h = 0.1450).
- Non-crossing quantiles — Fitted quantiles increase with τ for every row.
- Linear conditional quantile — No assumption about the error distribution; the τ-th quantile of the outcome is assumed linear in the predictors, with independent rows.
Coefficients for the 0.5 quantile
| Term | B | SE | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| (Intercept) | 4.288 | 0.4119 | 10.411 | < .001 | 3.478 | 5.099 |
| income | 0.3386 | 0.0135 | 25.064 | < .001 | 0.3120 | 0.3652 |
| area: suburban | 0.5571 | 0.4438 | 1.255 | .210 | −0.3163 | 1.431 |
| area: urban | 2.440 | 0.5410 | 4.510 | < .001 | 1.375 | 3.505 |
Each slope is the change in the 0.5 quantile of spending per unit of the predictor (or versus the reference level).
Quantile process
| τ | Term | B | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| 0.1000 | (Intercept) | 1.912 | 0.6723 | 0.5891 | 3.235 |
| 0.1000 | income | 0.2694 | 0.0190 | 0.2319 | 0.3069 |
| 0.1000 | area: suburban | 1.735 | 0.7356 | 0.2876 | 3.183 |
| 0.1000 | area: urban | 3.437 | 0.7361 | 1.988 | 4.886 |
| 0.2500 | (Intercept) | 3.422 | 0.7086 | 2.027 | 4.816 |
| 0.2500 | income | 0.2841 | 0.0125 | 0.2596 | 0.3086 |
| 0.2500 | area: suburban | 1.528 | 0.6710 | 0.2071 | 2.848 |
| 0.2500 | area: urban | 2.934 | 0.7255 | 1.506 | 4.362 |
| 0.5000 | (Intercept) | 4.288 | 0.4119 | 3.478 | 5.099 |
| 0.5000 | income | 0.3386 | 0.0135 | 0.3120 | 0.3652 |
| 0.5000 | area: suburban | 0.5571 | 0.4438 | −0.3163 | 1.431 |
| 0.5000 | area: urban | 2.440 | 0.5410 | 1.375 | 3.505 |
| 0.7500 | (Intercept) | 4.117 | 0.5852 | 2.965 | 5.268 |
| 0.7500 | income | 0.3877 | 0.0154 | 0.3574 | 0.4179 |
| 0.7500 | area: suburban | 1.062 | 0.5917 | −0.1022 | 2.227 |
| 0.7500 | area: urban | 4.205 | 0.6380 | 2.950 | 5.461 |
| 0.9000 | (Intercept) | 5.336 | 0.8480 | 3.667 | 7.005 |
| 0.9000 | income | 0.4058 | 0.0166 | 0.3732 | 0.4385 |
| 0.9000 | area: suburban | 1.387 | 0.8519 | −0.2892 | 3.064 |
| 0.9000 | area: urban | 3.884 | 0.7886 | 2.332 | 5.436 |
Slopes that change with τ mean the predictor affects the spread or shape of the outcome, not only its location.
- Linear program solved exactly (HiGHS dual simplex, refit at the vertex); Hendricks–Koenker (nid) sandwich standard errors with t tests on n − k = 297 df.
- Pseudo-R¹ (Koenker–Machado) is 1 − check loss of the model / check loss of the intercept-only quantile.
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
- Median heteroscedasticc3_quantile · outcome: spending · predictors: income, area
- Upper quantile kernelc3_quantile · outcome: spending · predictors: income
- Lower quantile interactionc3_quantile · outcome: spending · predictors: income, household
- Degenerate constantc3_quantile · outcome: spending · predictors: income, area
- Degenerate n3c3_quantile · outcome: spending · predictors: income, area
- Degenerate single levelc3_quantile · outcome: spending · predictors: income, area
In the guides
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
- Robust, permutation and exact methods · Statistics Guide · Step 3 — If assumptions are violated
- Regression (linear, logistic, Poisson) · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Outcomenumeric · 1 column
- The numeric variable whose quantile (median, 90th percentile …) you model.
- Predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
- Numeric predictors enter as is; categorical ones as dummy variables against their first level.
Choices you make
hypothesis
- Quantile (τ)default 0.5
0.5 is the median; 0.9 models the 90th percentile of the outcome given the predictors.
- Confidence leveldefault 0.95
Coverage of the coefficient intervals; 0.95 gives 95% intervals and tests at α = 0.05.
statistics
- Standard errorsdefault nid
Both are sandwich estimators that stay valid when the error spread changes with the predictors.
- Hendricks–Koenker (nid, recommended)(default) — Sandwich with a local density per row from fits at τ ± h; allows the spread to vary with the predictors.
- Powell kernel — Sandwich with kernel density estimates of the residuals at zero; also heteroscedasticity-robust.
- Interactionsdefault none
Interaction terms let one predictor's effect depend on another's value.
- None (main effects only)(default) — Each predictor's effect is the same whatever the other predictors' values.
- First two predictors (A × B) — The first two predictors' effects may depend on each other (one product term).
- All pairs of predictors — Every pair of predictors gets a product term; needs many rows per coefficient.
- Quantile process (τ = 0.1, 0.25, 0.5, 0.75, 0.9)default on
Refits at five quantiles to show how each effect changes across the distribution and to check that the fitted quantiles never cross.
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.
Unique solution
With tied outcomes or a whole-number n·τ, many coefficient values can fit equally well; any of them is a valid estimate.
Local density estimates
nid standard errors estimate the density at the quantile for each row; non-positive estimates (fits crossing at τ ± h) drop out.
Non-crossing quantiles
Fitted quantile lines for increasing τ should not cross within the data; crossing suggests a misspecified (e.g. non-linear) model.
- If violated → Add pairwise interactions — Crossing quantile lines often mean the effect of one predictor depends on another or is non-linear; a richer model can remove the crossing. Changes the question: Main effects become conditional effects (at 0 or the reference level of the other predictor).
Linear conditional quantile
The chosen quantile of the outcome changes linearly with the predictors; no error distribution is assumed.
What it reports
- Tests: All slopes zero at τ (Wald F)
- tau
- A rank test of whether a series tends to rise (or fall) over time — S counts later values above earlier ones minus those below.
- n
- How many independent units the analysis used; it sets precision and power.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- r1
- Models a chosen percentile of the outcome given the predictors, rather than its mean. It makes no normality assumption.
- loss
- Models a chosen percentile of the outcome given the predictors, rather than its mean. It makes no normality assumption.
- loss_null
- Models a chosen percentile of the outcome given the predictors, rather than its mean. It makes no normality assumption.
- wald_f
- The ratio of explained to unexplained variance, used by ANOVA and regression tests.
- wald_df1
- How much independent information is left to estimate variability after fitting the model.
- wald_df2
- How much independent information is left to estimate variability after fitting the model.
- wald_p
- Tests a parameter by dividing its estimate by its standard error; quick, but unreliable near boundaries or with separation.
- nonunique
- Models a chosen percentile of the outcome given the predictors, rather than its mean. It makes no normality assumption.
- n_nonpositive
- How many independent units the analysis used; it sets precision and power.
- bandwidth
- Models a chosen percentile of the outcome given the predictors, rather than its mean. It makes no normality assumption.
- se_type
- Standard errors that stay valid when residual variance is not constant; HC3 suits small samples.
- n_crossing
- How many independent units the analysis used; it sets precision and power.
- crossing_share
- Models a chosen percentile of the outcome given the predictors, rather than its mean. It makes no normality assumption.
- n_params
- How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.
- max_interaction_order
- The most factors combined in one term of the model: 1 means main effects only, 2 two-way interactions.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
Per group, level or term: coef[<term>], se[…], t[…], p[…], ci_low[…], ci_high[…], qcoef[<tau>|<term>], qse[…], qci_low[…], qci_high[…]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, quantreg, codesplashr.
Default traps between the two languages
- With no effect the nid Wald test rejects 6.1% at n = 100, 5.8% at n = 200 and 5.4% at n = 400 at the 5% level (10,000 samples each): the sparsity estimate is noisy in small samples (Koenker 2005, section 3.4).
- Python solves the linear program with HiGHS (scipy linprog, dual simplex), R with quantreg's Barrodale–Roberts simplex; both refit exactly at the vertex, so unique solutions agree to rounding.
- When the solution is not unique (flagged in the result), the engines may return different optimal coefficients with the same check loss.
- quantreg's summary.rq defaults to rank-inversion intervals for n < 1001; CodeSplash reports the nid (or Powell kernel) sandwich, which summary.rq gives with se = "nid" / "ker".
The exact script CodeSplash ran for example “Median heteroscedastic” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Quantile regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.quantile 1.0.1 · spec bf40b7cc4cd28401
# Dataset: c3_quantile (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 quantreg as csqr
from codesplash.stats import regression as csreg
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c3_quantile.parquet", columns=["spending", "income", "area"])
n_input = len(df)
df["area"] = pd.Categorical(df["area"], categories=["rural", "suburban", "urban"]) # stored level order
df = df.dropna(subset=["spending", "income", "area"]) # listwise deletion over the analysis columns
df["area"] = df["area"].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, ["spending", "income", "area"]) # infinite values stop the run (registry/errors.yaml)
# %% Design matrix
outcome = "spending"
predictors = ["income", "area"]
tau = 0.5 # the conditional quantile modeled (0.5 = median)
se_type = "nid" # nid (Hendricks–Koenker) | ker (Powell kernel)
interactions = "none" # none | first-two | all-pairs
process = True
conf = 0.95
if not 0 < tau < 1:
raise ValueError("The quantile τ must lie strictly between 0 and 1.")
# Treatment contrasts: the first stored level of each categorical predictor is the reference.
X = csreg.design_matrix(df, predictors, interactions)
n, k = X.shape
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
cs.check_rows(n, k + 2, "Quantile regression") # at least two more rows than coefficients
for col in [outcome] + predictors:
check_not_constant(df[col], col) # one value (or one level with data) is no variation
if np.linalg.matrix_rank(X.to_numpy()) < X.shape[1]:
cs.cs_error("CS_E_COLLINEAR")
terms = list(X.columns)
Xv = X.to_numpy(dtype=float)
y = df[outcome].to_numpy(dtype=float)
def covariance(t, b):
return csqr.cov_nid(Xv, y, t) if se_type == "nid" else csqr.cov_ker(Xv, y, t, b)
# %% Fit: the linear program, refit exactly at its vertex (identical in R)
beta, basis = csqr.rq_fit(Xv, y, tau)
nonunique = csqr.nonunique(Xv, y, tau, beta, basis)
cv = covariance(tau, beta)
V = cv["cov"]
se = np.sqrt(np.diag(V))
dfree = n - k
tval = beta / se
pval = 2 * stats.t.sf(np.abs(tval), dfree)
crit = stats.t.ppf(1 - (1 - conf) / 2, dfree)
loss = csqr.check_loss(y - Xv @ beta, tau)
loss0 = csqr.null_loss(y, tau)
r1 = 1 - loss / loss0 if loss0 > 0 else None # Koenker–Machado pseudo-R¹
slopes = list(range(1, k))
wald_f = float(beta[slopes] @ np.linalg.solve(V[np.ix_(slopes, slopes)], beta[slopes])) / len(slopes)
wald_p = float(stats.f.sf(wald_f, len(slopes), dfree))
# %% Quantile process
taus = sorted({0.1, 0.25, 0.5, 0.75, 0.9, round(tau, 10)}) if process else [tau]
process_rows, fitted = [], []
values = {}
for t in taus:
b_t = beta if t == tau else csqr.rq_fit(Xv, y, t)[0]
fitted.append(Xv @ b_t)
if not process:
continue
se_t = se if t == tau else np.sqrt(np.diag(covariance(t, b_t)["cov"]))
for j, term in enumerate(terms):
row = {"tau": float(t), "term": term, "estimate": float(b_t[j]), "se": float(se_t[j]),
"ci_low": float(b_t[j] - crit * se_t[j]), "ci_high": float(b_t[j] + crit * se_t[j])}
process_rows.append(row)
key = f"{t:g}|{term}"
values.update({f"qcoef[{key}]": row["estimate"], f"qse[{key}]": row["se"], f"qci_low[{key}]": row["ci_low"], f"qci_high[{key}]": row["ci_high"]})
n_crossing = csqr.crossing(np.column_stack(fitted)) if process else None
# %% Assumptions
assumptions = [
{"key": "uniqueness", "label": "Unique solution", "status": "warn" if nonunique else "pass",
"detail": "Other coefficient values fit equally well (the optimum is a face, typical with tied outcomes or a whole-number n·τ); the estimate shown is one of them." if nonunique
else "The optimal coefficients are unique."},
]
if se_type == "nid":
bad = cv["n_nonpositive"]
assumptions.append({"key": "sparsity", "label": "Local density estimates", "status": "warn" if bad else "pass", "statistic": bad,
"detail": (f"{bad} of {n} local density estimates were not positive (the fits at τ ± h cross there) and were set to zero." if bad
else f"All {n} local density estimates are positive (bandwidth h = {cv['bandwidth']:.4f}).")})
if process:
share = n_crossing / n
assumptions.append({"key": "crossing", "label": "Non-crossing quantiles", "status": "warn" if n_crossing else "pass", "statistic": n_crossing,
"detail": (f"Fitted quantiles for increasing τ cross for {n_crossing} of {n} rows ({share:.1%}); the linear model may not hold across the distribution." if n_crossing
else "Fitted quantiles increase with τ for every row.")})
assumptions.append({"key": "linearity", "label": "Linear conditional quantile", "status": "info",
"detail": "No assumption about the error distribution; the τ-th quantile of the outcome is assumed linear in the predictors, with independent rows."})
# %% Result
coefs = [{"term": t, "estimate": float(beta[j]), "se": float(se[j]), "t": float(tval[j]), "p": float(pval[j]),
"ci_low": float(beta[j] - crit * se[j]), "ci_high": float(beta[j] + crit * se[j])} for j, t in enumerate(terms)]
for c in coefs:
values.update({f"{key}[{c['term']}]": c[key] if key != "coef" else c["estimate"] for key in ("coef", "se", "t", "p", "ci_low", "ci_high")})
values.update({"tau": tau, "n": n, "k": k, "r1": r1, "loss": loss, "loss_null": loss0, "wald_f": wald_f, "wald_df1": float(len(slopes)),
"wald_df2": float(dfree), "wald_p": wald_p, "nonunique": nonunique, "n_nonpositive": cv["n_nonpositive"], "bandwidth": cv["bandwidth"],
"se_type": se_type, "n_crossing": n_crossing, "crossing_share": (n_crossing / n) if process else None, "n_params": k,
"max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1,
"missing_share": n_dropped / n_input if n_input else 0.0})
name = "Median regression" if tau == 0.5 else f"Quantile regression (τ = {tau:g})"
significant = [c["term"] for c in coefs[1:] if c["p"] < 1 - conf]
summary = (f"{name} of {outcome} (n = {n}): Wald F({len(slopes)}, {dfree}) = {wald_f:.2f}, {cs.fmt_p(wald_p)}; pseudo-R¹ = {r1:.3f}. "
+ (f"Significant terms: {', '.join(significant)}." if significant else "No individual term is significant."))
pct = f"{conf:.0%}"
se_name = {"nid": "Hendricks–Koenker (nid) sandwich", "ker": "Powell kernel sandwich"}[se_type]
tables = [
{"key": "coefficients", "title": f"Coefficients for the {tau:g} quantile", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "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": coefs, "note": f"Each slope is the change in the {tau:g} quantile of {outcome} per unit of the predictor (or versus the reference level)."},
]
charts = [cs.chart("coefficients", "forest", f"Slopes at τ = {tau:g}", {
"label": cs.col("Term", [c["term"] for c in coefs[1:]], kind="categorical"), "estimate": cs.col("B", [c["estimate"] for c in coefs[1:]]),
"low": cs.col("low", [c["ci_low"] for c in coefs[1:]]), "high": cs.col("high", [c["ci_high"] for c in coefs[1:]])}, controls={"reference": 0})]
if process:
tables.append({"key": "process", "title": "Quantile process", "columns": [
{"key": "tau", "label": "τ", "type": "number"}, {"key": "term", "label": "Term", "type": "string"},
{"key": "estimate", "label": "B", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": process_rows, "note": "Slopes that change with τ mean the predictor affects the spread or shape of the outcome, not only its location."})
slope_rows = [r for r in process_rows if r["term"] != "(Intercept)"]
charts.append(cs.chart("process", "line", "Slopes across quantiles", {
"x": cs.col("τ", [r["tau"] for r in slope_rows]), "y": cs.col("B", [r["estimate"] for r in slope_rows]),
"group": cs.col("Term", [r["term"] for r in slope_rows], kind="categorical", levels=terms[1:])}))
cs.publish({
"method": "regression.quantile",
"methodVersion": "1.0.1",
"title": name,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"pseudo-R¹ = {cs.fmt_num(r1, 3)}, Wald F({len(slopes)}, {dfree}) = {wald_f:.2f}, {cs.fmt_p(wald_p)}",
"statistics": [{"key": "wald_f", "label": "Wald F", "value": wald_f}, {"key": "wald_p", "label": "p", "value": wald_p, "format": "p"},
{"key": "r1", "label": "Pseudo-R¹", "value": r1}],
"tables": tables,
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Linear program solved exactly (HiGHS dual simplex, refit at the vertex); {se_name} standard errors with t tests on n − k = {dfree} df.",
"Pseudo-R¹ (Koenker–Machado) is 1 − check loss of the model / check loss of the intercept-only quantile."],
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Median heteroscedastic” · R version 4.5.1 (2025-06-13)
# Quantile regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.quantile 1.0.1 · spec bf40b7cc4cd28401
# Dataset: c3_quantile (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/c3_quantile.parquet", col_select = c("spending", "income", "area")))
n_input <- nrow(df)
df[["area"]] <- factor(df[["area"]], levels = c("rural", "suburban", "urban")) # stored level order
df <- df[stats::complete.cases(df[c("spending", "income", "area")]), , 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("spending", "income", "area")) # infinite values stop the run (registry/errors.yaml)
# %% Design matrix
outcome <- "spending"
predictors <- c("income", "area")
tau <- 0.5 # the conditional quantile modeled (0.5 = median)
se_type <- "nid" # nid (Hendricks-Koenker) | ker (Powell kernel)
interactions <- "none" # none | first-two | all-pairs
process <- TRUE
conf <- 0.95
if (!(tau > 0 && tau < 1)) stop("The quantile τ must lie strictly between 0 and 1.")
# Treatment contrasts: the first stored level of each categorical predictor is the reference.
terms <- cs_design_labels(df, predictors, interactions)
n <- nrow(df)
k <- length(terms)
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_rows(n, k + 2, "Quantile regression") # at least two more rows than coefficients
for (col in c(outcome, predictors)) cs_check_not_constant(df[[col]], col) # one value (or one level with data) is no variation
X <- model.matrix(cs_model_formula(outcome, predictors, interactions), data = df)
stopifnot(length(terms) == ncol(X))
colnames(X) <- terms
if (qr(X)$rank < ncol(X)) cs_error("CS_E_COLLINEAR")
y <- as.numeric(df[[outcome]])
covariance <- function(t, b) if (se_type == "nid") cs_rq_cov_nid(X, y, t) else cs_rq_cov_ker(X, y, t, b)
# %% Fit: quantreg's simplex, refit exactly at its vertex (identical in Python)
fit <- cs_rq_fit(X, y, tau)
beta <- fit$beta
nonunique <- cs_rq_nonunique(X, y, tau, beta, fit$h)
cv <- covariance(tau, beta)
V <- cv$cov
se <- sqrt(diag(V))
dfree <- n - k
tval <- beta / se
pval <- 2 * pt(abs(tval), dfree, lower.tail = FALSE)
crit <- qt(1 - (1 - conf) / 2, dfree)
loss <- cs_rq_check_loss(y - drop(X %*% beta), tau)
loss0 <- cs_rq_null_loss(y, tau)
r1 <- if (loss0 > 0) 1 - loss / loss0 else NULL # Koenker-Machado pseudo-R1
slopes <- 2:k
wald_f <- sum(beta[slopes] * solve(V[slopes, slopes, drop = FALSE], beta[slopes])) / length(slopes)
wald_p <- pf(wald_f, length(slopes), dfree, lower.tail = FALSE)
# %% Quantile process
taus <- if (process) sort(unique(c(0.1, 0.25, 0.5, 0.75, 0.9, round(tau, 10)))) else tau
process_rows <- list()
fitted <- NULL
values <- list()
for (t in taus) {
b_t <- if (t == tau) beta else cs_rq_fit(X, y, t)$beta
fitted <- cbind(fitted, drop(X %*% b_t))
if (!process) next
se_t <- if (t == tau) se else sqrt(diag(covariance(t, b_t)$cov))
for (j in seq_along(terms)) {
row <- list(tau = t, term = terms[j], estimate = b_t[j], se = se_t[j], ci_low = b_t[j] - crit * se_t[j], ci_high = b_t[j] + crit * se_t[j])
process_rows[[length(process_rows) + 1]] <- row
key <- sprintf("%s|%s", sprintf("%g", t), terms[j])
values[[sprintf("qcoef[%s]", key)]] <- row$estimate
values[[sprintf("qse[%s]", key)]] <- row$se
values[[sprintf("qci_low[%s]", key)]] <- row$ci_low
values[[sprintf("qci_high[%s]", key)]] <- row$ci_high
}
}
n_crossing <- if (process) cs_rq_crossing(fitted) else NULL
# %% Assumptions
assumptions <- list(list(key = "uniqueness", label = "Unique solution", status = if (nonunique) "warn" else "pass",
detail = if (nonunique) "Other coefficient values fit equally well (the optimum is a face, typical with tied outcomes or a whole-number n·τ); the estimate shown is one of them." else "The optimal coefficients are unique."))
if (se_type == "nid") {
bad <- cv$n_nonpositive
assumptions[[length(assumptions) + 1]] <- list(key = "sparsity", label = "Local density estimates", status = if (bad > 0) "warn" else "pass", statistic = bad,
detail = if (bad > 0) sprintf("%d of %d local density estimates were not positive (the fits at τ ± h cross there) and were set to zero.", bad, n)
else sprintf("All %d local density estimates are positive (bandwidth h = %.4f).", n, cv$bandwidth))
}
if (process) {
assumptions[[length(assumptions) + 1]] <- list(key = "crossing", label = "Non-crossing quantiles", status = if (n_crossing > 0) "warn" else "pass", statistic = n_crossing,
detail = if (n_crossing > 0) sprintf("Fitted quantiles for increasing τ cross for %d of %d rows (%.1f%%); the linear model may not hold across the distribution.", n_crossing, n, 100 * n_crossing / n)
else "Fitted quantiles increase with τ for every row.")
}
assumptions[[length(assumptions) + 1]] <- list(key = "linearity", label = "Linear conditional quantile", status = "info",
detail = "No assumption about the error distribution; the τ-th quantile of the outcome is assumed linear in the predictors, with independent rows.")
# %% Result
coefs <- lapply(seq_along(terms), function(j) list(term = terms[j], estimate = unname(beta[j]), se = unname(se[j]), t = unname(tval[j]), p = unname(pval[j]),
ci_low = unname(beta[j] - crit * se[j]), ci_high = unname(beta[j] + crit * se[j])))
for (cf in coefs) {
for (key in c("coef", "se", "t", "p", "ci_low", "ci_high")) values[[sprintf("%s[%s]", key, cf$term)]] <- if (key == "coef") cf$estimate else cf[[key]]
}
values <- c(values, list(tau = tau, n = n, k = k, r1 = r1, loss = loss, loss_null = loss0, wald_f = wald_f, wald_df1 = length(slopes),
wald_df2 = dfree, wald_p = wald_p, nonunique = nonunique, n_nonpositive = cv$n_nonpositive, bandwidth = cv$bandwidth,
se_type = se_type, n_crossing = n_crossing, crossing_share = if (process) n_crossing / n else NULL, n_params = k,
max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1,
missing_share = if (n_input > 0) n_dropped / n_input else 0))
name <- if (tau == 0.5) "Median regression" else sprintf("Quantile regression (τ = %s)", sprintf("%g", tau))
significant <- vapply(Filter(function(cf) cf$p < 1 - conf, coefs[-1]), `[[`, "", "term")
summary <- paste0(sprintf("%s of %s (n = %d): Wald F(%d, %d) = %.2f, %s; pseudo-R¹ = %.3f. ", name, outcome, n, length(slopes), dfree, wald_f, cs_fmt_p(wald_p), r1),
if (length(significant)) sprintf("Significant terms: %s.", paste(significant, collapse = ", ")) else "No individual term is significant.")
pct <- sprintf("%.0f%%", conf * 100)
se_name <- c(nid = "Hendricks–Koenker (nid) sandwich", ker = "Powell kernel sandwich")[[se_type]]
tables <- list(list(key = "coefficients", title = sprintf("Coefficients for the %s quantile", sprintf("%g", tau)), columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", 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 = coefs, note = sprintf("Each slope is the change in the %s quantile of %s per unit of the predictor (or versus the reference level).", sprintf("%g", tau), outcome)))
sl <- coefs[-1]
charts <- list(cs_chart("coefficients", "forest", sprintf("Slopes at τ = %s", sprintf("%g", tau)), list(
label = cs_col("Term", vapply(sl, `[[`, "", "term"), kind = "categorical"), estimate = cs_col("B", vapply(sl, `[[`, 0, "estimate")),
low = cs_col("low", vapply(sl, `[[`, 0, "ci_low")), high = cs_col("high", vapply(sl, `[[`, 0, "ci_high"))), controls = list(reference = 0)))
if (process) {
tables[[2]] <- list(key = "process", title = "Quantile process", columns = list(
list(key = "tau", label = "τ", type = "number"), list(key = "term", label = "Term", type = "string"),
list(key = "estimate", label = "B", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
rows = process_rows, note = "Slopes that change with τ mean the predictor affects the spread or shape of the outcome, not only its location.")
sr <- Filter(function(r) r$term != "(Intercept)", process_rows)
charts[[2]] <- cs_chart("process", "line", "Slopes across quantiles", list(
x = cs_col("τ", vapply(sr, `[[`, 0, "tau")), y = cs_col("B", vapply(sr, `[[`, 0, "estimate")),
group = cs_col("Term", vapply(sr, `[[`, "", "term"), kind = "categorical", levels = terms[-1])))
}
cs_publish(list(
method = "regression.quantile",
methodVersion = "1.0.1",
title = name,
engine = cs_engine_info("stats", "quantreg", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("pseudo-R¹ = %s, Wald F(%d, %d) = %.2f, %s", cs_fmt_num(r1, 3), length(slopes), dfree, wald_f, cs_fmt_p(wald_p)),
statistics = list(list(key = "wald_f", label = "Wald F", value = wald_f), list(key = "wald_p", label = "p", value = wald_p, format = "p"),
list(key = "r1", label = "Pseudo-R¹", value = r1)),
tables = tables,
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Linear program solved exactly (quantreg Barrodale–Roberts, refit at the vertex); %s standard errors with t tests on n − k = %d df.", se_name, dfree),
"Pseudo-R¹ (Koenker–Machado) is 1 − check loss of the model / check loss of the intercept-only quantile."),
charts = charts,
values = values
))
Sources
- Koenker, R., & Bassett, G. (1978). Regression quantiles. Econometrica, 46, 33–50.
- Koenker, R. (2005). Quantile Regression. Cambridge University Press.
- Koenker, R., & Machado, J. A. F. (1999). Goodness of fit and related inference processes for quantile regression. JASA, 94, 1296–1310.
- Hendricks, W., & Koenker, R. (1992). Hierarchical spline models for conditional quantiles and the demand for electricity. JASA, 87, 58–68.
- Hall, P., & Sheather, S. J. (1988). On the distribution of a studentized quantile. JRSS B, 50, 381–391.
From the CodeSplash method registry · regression.quantile v1.0.1.