Skip to content

DRegression models · regression.censored

Censored regression (Tobit)

How do predictors affect a numeric outcome that piles up at a limit (zero hours, a detection limit, a top code)?

Tobit (censored-normal) regression by maximum likelihood with a lower limit, an upper limit or both: coefficients on the latent outcome with z tests and intervals, σ, the likelihood-ratio test against the intercept-only model, average marginal effects on the observed mean, and McDonald–Moffitt's decomposition of each effect into a change in the uncensored mean and a change in the probability of being uncensored. OLS on such data is biased toward zero; Tobit assumes a normal, constant-variance latent outcome.

Verified in Python and R Python and R agree to 10 decimals Also called Tobit, Tobit model, censored normal regression…

A real result

Example “Left censored at zero”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Censored regression (Tobit)Recorded · Python and R agreeRecorded 2026-11-17 · 60 values compared
R

χ²(4, N = 400) = 185.65, p < .001, σ = 4.24

LR χ²
185.65
p
< .001
σ
4.241
Censored
13.3%

Plots

Effects on the latent outcomeHow large are several estimates, how precise, and which exclude the null?
View data
BhighTermlow
0.83030.9908educ0.6698
0.23020.2808exper0.1796
−1.577−1.093kids−2.061
2.0262.922union: true1.130
Observed outcome against the fitted latent meanHow does a Tobit model's latent mean relate to outcomes that pile up at a limit?
View data
Fitted latent mean (x′β)hoursCensoring
4.0446.083observed
2.4059.452observed
4.3140left-censored
6.2802.094observed
5.6630left-censored
9.95514.405observed
9.2995.388observed
8.4868.341observed
5.9876.467observed
1.4780left-censored
8.83110.231observed
6.91411.441observed
7.90911.074observed
9.8874.404observed
1.1930left-censored
1.2065.914observed
8.4104.877observed
8.2290.7510observed
5.8459.805observed
12.86210.335observed
4.5118.118observed
4.1019.481observed
1.9760left-censored
6.6256.232observed
5.5084.294observed
9.9568.475observed
1.5421.665observed
4.8914.889observed
7.6118.561observed
7.76412.321observed
8.8698.656observed
5.4907.640observed
7.4912.260observed
5.0720.6890observed
12.53513.229observed
4.3709.310observed
4.7881.897observed
12.60413.732observed
7.1009.390observed
10.37412.967observed
7.8485.799observed
1.4790left-censored
1.4880left-censored
7.6798.334observed
−0.74921observed
9.7597.401observed
2.8970left-censored
5.04012.324observed
7.3132.202observed
2.0311.629observed
4.2903.799observed
6.0064.971observed
8.77214.641observed
5.4925.825observed
8.06814.836observed
4.81810.417observed
7.09114.886observed
7.1596.423observed
1.8818.988observed
3.7260.9130observed

First 60 of 400 rows.

Assumptions

  • Share censored — 53 rows at the lower and 0 at the upper limit (13% censored).
  • Maximum likelihood converged — Newton–Raphson converged in 5 iterations.
  • Normal latent errors with constant variance — Not testable directly from censored data; if in doubt compare with quantile regression at a quantile above the censoring point.

Coefficients (latent outcome) and average marginal effects

TermBSEzp95% CI low95% CI highEffect on E[y]
(Intercept)−6.9391.118−6.207< .001−9.130−4.748—
educ0.83030.081910.138< .0010.66980.99080.7150
exper0.23020.02588.919< .0010.17960.28080.1983
kids−1.5770.2471−6.383< .001−2.061−1.093−1.358
union: true2.0260.45734.431< .0011.1302.9221.745

B is the effect on the latent (uncensored) outcome; the effect on the observed mean is B × 0.861, the average probability of being uncensored.

  • Maximum likelihood (Newton–Raphson from OLS, 5 iterations); covariance from the observed information; Wald z tests; σ = 4.2415 (SE by the delta method from log σ).
Python

χ²(4, N = 400) = 185.65, p < .001, σ = 4.24

LR χ²
185.65
p
< .001
σ
4.241
Censored
13.3%

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Share censored — 53 rows at the lower and 0 at the upper limit (13% censored).
  • Maximum likelihood converged — Newton–Raphson converged in 5 iterations.
  • Normal latent errors with constant variance — Not testable directly from censored data; if in doubt compare with quantile regression at a quantile above the censoring point.

Coefficients (latent outcome) and average marginal effects

TermBSEzp95% CI low95% CI highEffect on E[y]
(Intercept)−6.9391.118−6.207< .001−9.130−4.748—
educ0.83030.081910.138< .0010.66980.99080.7150
exper0.23020.02588.919< .0010.17960.28080.1983
kids−1.5770.2471−6.383< .001−2.061−1.093−1.358
union: true2.0260.45734.431< .0011.1302.9221.745

B is the effect on the latent (uncensored) outcome; the effect on the observed mean is B × 0.861, the average probability of being uncensored.

  • Maximum likelihood (Newton–Raphson from OLS, 5 iterations); covariance from the observed information; Wald z tests; σ = 4.2415 (SE by the delta method from log σ).

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

  • Left censored at zeroc3_tobit · outcome: hours · predictors: educ, exper, kids, union
  • Two limitsc3_tobit · outcome: hours_capped · predictors: educ, exper, kids
  • Right onlyc3_tobit · outcome: hours_capped · predictors: educ, union
  • Degenerate constantc3_tobit · outcome: hours · predictors: educ, exper, kids, union
  • Degenerate n3c3_tobit · outcome: hours · predictors: educ, exper, kids, union

In the guides

Where it sits in the decision guides

  • Continuous outcome: linear regression · Statistics Guide · D — Predict an outcome
  • Interval censoring, recurrent events, delayed entry · Statistics Guide · F — Time-to-event analysis
  • Generalized models · Statistics Guide · Step 3 — If assumptions are violated

What you need

Outcomenumeric · 1 column
Censored values must equal the limit (e.g. 0 hours, or the top code).
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

Lower limitdefault 0

Values at or below this are censored (the true value is this or less). Leave empty when nothing is censored from below.

Upper limitdefault —

Values at or above this are censored (top-coded). Leave empty when nothing is censored from above.

Confidence leveldefault 0.95

Coverage of the coefficient intervals; 0.95 gives 95% intervals and tests at α = 0.05.

statistics

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.

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.

  • Share censored

    Tobit fills in what censoring hides from the normal shape of the outcome; with over half censored, that assumption drives the answer.

  • Maximum likelihood converged

    Newton–Raphson must reach the maximum of the likelihood; if it does not, the estimates and standard errors are unreliable.

  • Normal latent errors with constant variance

    Unlike OLS, Tobit's coefficients are biased if the latent errors are not normal or not homoscedastic.

What it reports

  • Tests: All slopes zero (likelihood ratio)
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.
n_left
How many independent units the analysis used; it sets precision and power.
n_right
How many independent units the analysis used; it sets precision and power.
n_uncensored
How many independent units the analysis used; it sets precision and power.
censored_share
Follow-up ended before the event happened, so you only know the event time is later than observed.
left
Regression for a numeric outcome observed only inside limits, assuming a normal latent outcome lies behind it.
right
Regression for a numeric outcome observed only inside limits, assuming a normal latent outcome lies behind it.
sigma
The distance between two distributions' average kernel embeddings; zero when they are equal.
sigma_se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
log_sigma
Regression for a numeric outcome observed only inside limits, assuming a normal latent outcome lies behind it.
log_lik
The logarithm of the likelihood; higher (less negative) means the model fits the data better.
log_lik_null
How well a model with no predictors fits. The likelihood-ratio test compares the fitted model with it.
lr_chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
lr_df
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.
aic
A model score balancing fit against complexity; lower is better, and only differences matter.
bic
Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
scale_factor
Regression for a numeric outcome observed only inside limits, assuming a normal latent outcome lies behind it.
prob_uncensored
Regression for a numeric outcome observed only inside limits, assuming a normal latent outcome lies behind it.
mm_share
Regression for a numeric outcome observed only inside limits, assuming a normal latent outcome lies behind it.
converged
Whether an iterative fit found a stable solution; warnings mean estimates may be unreliable.
iterations
Whether an iterative fit found a stable solution; warnings mean estimates may be unreliable.
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[…], z[…], p[…], ci_low[…], ci_high[…], ame[<term>]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-8). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines maximize the likelihood with the same Newton–Raphson twin (codesplash.stats.tobit ↔ cs_tobit_fit) from the OLS start; AER::tobit / survival::survreg give the same estimates to their convergence tolerance (~1e-6).
Python

The exact script CodeSplash ran for example “Left censored at zero” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Censored regression (Tobit)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.censored 1.0.2 · spec 4770572910295758
# Dataset: c3_tobit (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 regression as csreg
from codesplash.stats import tobit as cstobit

# %% Data
df = pd.read_parquet("tests/parity/fixtures/c3_tobit.parquet", columns=["hours", "educ", "exper", "kids", "union"])
n_input = len(df)
df["union"] = pd.Categorical(df["union"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["hours", "educ", "exper", "kids", "union"])  # listwise deletion over the analysis columns
df["union"] = df["union"].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, ["hours", "educ", "exper", "kids", "union"])  # infinite values stop the run (registry/errors.yaml)

# %% Design matrix
outcome = "hours"
predictors = ["educ", "exper", "kids", "union"]
left = 0  # values at or below are censored (None = no lower limit)
right = None  # values at or above are censored (None = no upper limit)
interactions = "none"
conf = 0.95
if left is None and right is None:
    raise ValueError("Set a lower limit, an upper limit or both: without censoring, use linear regression.")
X = csreg.design_matrix(df, predictors, interactions)
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
cs.check_rows(len(df), X.shape[1] + 1, "Censored regression")  # 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")
n, k = X.shape
terms = list(X.columns)
Xv = X.to_numpy(dtype=float)
y = df[outcome].to_numpy(dtype=float)

# %% Fit: maximum likelihood (Newton–Raphson twin, identical in R)
fit = cstobit.tobit_fit(Xv, y, left, right)
null = cstobit.tobit_fit(np.ones((n, 1)), y, left, right)
b = fit["beta"]
se_all = np.sqrt(np.diag(fit["cov"]))
se = se_all[:k]
zval = b / se
pval = 2 * stats.norm.sf(np.abs(zval))
crit = stats.norm.ppf(1 - (1 - conf) / 2)
sigma = fit["sigma"]
sigma_se = sigma * se_all[k]  # delta method from log σ
lr = 2 * (fit["loglik"] - null["loglik"])
lr_df = k - 1
lr_p = float(stats.chi2.sf(lr, lr_df))
aic = -2 * fit["loglik"] + 2 * (k + 1)
bic = -2 * fit["loglik"] + np.log(n) * (k + 1)
eff = cstobit.tobit_effects(Xv, b, sigma, left, right)
censored = fit["n_left"] + fit["n_right"]

# %% Assumptions
share = censored / n
assumptions = [
    {"key": "censoring", "label": "Share censored", "status": "warn" if share > 0.5 else ("info" if censored else "warn"), "statistic": share,
     "detail": (f"{fit['n_left']} rows at the lower and {fit['n_right']} at the upper limit ({share:.0%} censored)"
                + ("; with more than half censored the normal-shape assumption drives the estimates." if share > 0.5
                   else "." if censored else "; no row is censored, so ordinary linear regression gives the same answer."))},
    {"key": "convergence", "label": "Maximum likelihood converged", "status": "pass" if fit["converged"] else "fail",
     "detail": f"Newton–Raphson converged in {fit['iterations']} iterations." if fit["converged"] else "The likelihood did not converge; estimates are unreliable."},
    {"key": "normality", "label": "Normal latent errors with constant variance", "status": "info",
     "detail": "Not testable directly from censored data; if in doubt compare with quantile regression at a quantile above the censoring point."},
]

# %% Result
coefs = [{"term": t, "estimate": float(b[j]), "se": float(se[j]), "z": float(zval[j]), "p": float(pval[j]),
          "ci_low": float(b[j] - crit * se[j]), "ci_high": float(b[j] + crit * se[j]),
          "ame": None if t == "(Intercept)" else float(eff["ame"][j])} for j, t in enumerate(terms)]
values = {}
for c in coefs:
    values.update({f"{key}[{c['term']}]": c[key] if key != "coef" else c["estimate"] for key in ("coef", "se", "z", "p", "ci_low", "ci_high")})
    if c["ame"] is not None:
        values[f"ame[{c['term']}]"] = c["ame"]
values.update({"n": n, "k": k, "n_left": fit["n_left"], "n_right": fit["n_right"], "n_uncensored": fit["n_uncensored"], "censored_share": share,
               "left": left, "right": right, "sigma": sigma, "sigma_se": float(sigma_se), "log_sigma": fit["log_sigma"], "log_lik": fit["loglik"],
               "log_lik_null": null["loglik"], "lr_chi2": float(lr), "lr_df": float(lr_df), "lr_p": lr_p, "aic": float(aic), "bic": float(bic),
               "scale_factor": eff["scale"], "prob_uncensored": eff["prob_uncensored"], "mm_share": eff["mm_share"], "converged": fit["converged"],
               "iterations": fit["iterations"], "n_params": k + 1, "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})
limits = " and ".join(([f"below at {left:g}"] if left is not None else []) + ([f"above at {right:g}"] if right is not None else []))
significant = [c["term"] for c in coefs[1:] if c["p"] < 1 - conf]
summary = (f"Tobit regression of {outcome} censored {limits} (n = {n}, {censored} censored): LR χ²({lr_df}) = {lr:.2f}, {cs.fmt_p(lr_p)}; σ = {sigma:.3f}. "
           + (f"Significant terms: {', '.join(significant)}." if significant else "No individual term is significant."))
pct = f"{conf:.0%}"
slopes = coefs[1:]
cs.publish({
    "method": "regression.censored",
    "methodVersion": "1.0.2",
    "title": "Censored regression (Tobit)",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"χ²({lr_df}, N = {n}) = {lr:.2f}, {cs.fmt_p(lr_p)}, σ = {sigma:.2f}",
    "statistics": [{"key": "lr_chi2", "label": "LR χ²", "value": float(lr)}, {"key": "lr_p", "label": "p", "value": lr_p, "format": "p"},
                   {"key": "sigma", "label": "σ", "value": sigma}, {"key": "censored_share", "label": "Censored", "value": share, "format": "percent"}],
    "tables": [
        {"key": "coefficients", "title": "Coefficients (latent outcome) and average marginal effects", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"},
            {"key": "se", "label": "SE", "type": "number"}, {"key": "z", "label": "z", "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"}, {"key": "ame", "label": "Effect on E[y]", "type": "number"}],
         "rows": coefs, "note": f"B is the effect on the latent (uncensored) outcome; the effect on the observed mean is B × {eff['scale']:.3f}, the average probability of being uncensored."},
    ],
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Maximum likelihood (Newton–Raphson from OLS, {fit['iterations']} iterations); covariance from the observed information; Wald z tests; "
              f"σ = {sigma:.4f} (SE by the delta method from log σ)."],
    "charts": [cs.chart("coefficients", "forest", "Effects on the latent outcome", {
        "label": cs.col("Term", [c["term"] for c in slopes], kind="categorical"), "estimate": cs.col("B", [c["estimate"] for c in slopes]),
        "low": cs.col("low", [c["ci_low"] for c in slopes]), "high": cs.col("high", [c["ci_high"] for c in slopes])}, controls={"reference": 0}),
        # Observed outcome against the fitted latent mean x′β, censored rows marked at their limit (Chart Lab `censored-fit`).
        cs.chart("fit", "censored-fit", "Observed outcome against the fitted latent mean", {
            "fitted": cs.col("Fitted latent mean (x′β)", [float(v) for v in Xv @ b], kind="numeric"),
            "observed": cs.col(outcome, [float(v) for v in y], kind="numeric"),
            "status": cs.col("Censoring", ["left-censored" if (left is not None and v <= left) else "right-censored" if (right is not None and v >= right) else "observed" for v in y],
                             kind="categorical")})],
    "values": values,
})
R

The exact script CodeSplash ran for example “Left censored at zero” · R version 4.5.1 (2025-06-13)

# Censored regression (Tobit)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.censored 1.0.2 · spec 4770572910295758
# Dataset: c3_tobit (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_tobit.parquet", col_select = c("hours", "educ", "exper", "kids", "union")))
n_input <- nrow(df)
df[["union"]] <- factor(df[["union"]], levels = c("false", "true"))  # stored level order
df <- df[stats::complete.cases(df[c("hours", "educ", "exper", "kids", "union")]), , 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("hours", "educ", "exper", "kids", "union"))  # infinite values stop the run (registry/errors.yaml)

# %% Design matrix
outcome <- "hours"
predictors <- c("educ", "exper", "kids", "union")
left <- 0  # values at or below are censored (NULL = no lower limit)
right <- NULL  # values at or above are censored (NULL = no upper limit)
interactions <- "none"
conf <- 0.95
if (is.null(left) && is.null(right)) stop("Set a lower limit, an upper limit or both: without censoring, use linear regression.")
terms <- cs_design_labels(df, predictors, interactions)
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_rows(nrow(df), length(terms) + 1, "Censored regression")  # 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")
n <- nrow(X)
k <- ncol(X)
y <- as.numeric(df[[outcome]])

# %% Fit: maximum likelihood (Newton-Raphson twin, identical in Python)
fit <- cs_tobit_fit(X, y, left, right)
null <- cs_tobit_fit(matrix(1, n, 1), y, left, right)
b <- fit$beta
se_all <- sqrt(diag(fit$cov))
se <- se_all[1:k]
zval <- b / se
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)
crit <- qnorm(1 - (1 - conf) / 2)
sigma <- fit$sigma
sigma_se <- sigma * se_all[k + 1]  # delta method from log sigma
lr <- 2 * (fit$loglik - null$loglik)
lr_df <- k - 1
lr_p <- pchisq(lr, lr_df, lower.tail = FALSE)
aic <- -2 * fit$loglik + 2 * (k + 1)
bic <- -2 * fit$loglik + log(n) * (k + 1)
eff <- cs_tobit_effects(X, b, sigma, left, right)
censored <- fit$n_left + fit$n_right

# %% Assumptions
share <- censored / n
assumptions <- list(
  list(key = "censoring", label = "Share censored", status = if (share > 0.5) "warn" else if (censored > 0) "info" else "warn", statistic = share,
       detail = paste0(sprintf("%d rows at the lower and %d at the upper limit (%.0f%% censored)", fit$n_left, fit$n_right, 100 * share),
                       if (share > 0.5) "; with more than half censored the normal-shape assumption drives the estimates." else if (censored > 0) "." else "; no row is censored, so ordinary linear regression gives the same answer.")),
  list(key = "convergence", label = "Maximum likelihood converged", status = if (fit$converged) "pass" else "fail",
       detail = if (fit$converged) sprintf("Newton–Raphson converged in %d iterations.", fit$iterations) else "The likelihood did not converge; estimates are unreliable."),
  list(key = "normality", label = "Normal latent errors with constant variance", status = "info",
       detail = "Not testable directly from censored data; if in doubt compare with quantile regression at a quantile above the censoring point.")
)

# %% Result
coefs <- lapply(seq_along(terms), function(j) list(term = terms[j], estimate = b[j], se = se[j], z = zval[j], p = pval[j],
                                                     ci_low = b[j] - crit * se[j], ci_high = b[j] + crit * se[j],
                                                     ame = if (terms[j] == "(Intercept)") NULL else eff$ame[j]))
values <- list()
for (cf in coefs) {
  for (key in c("coef", "se", "z", "p", "ci_low", "ci_high")) values[[sprintf("%s[%s]", key, cf$term)]] <- if (key == "coef") cf$estimate else cf[[key]]
  if (!is.null(cf$ame)) values[[sprintf("ame[%s]", cf$term)]] <- cf$ame
}
values <- c(values, list(n = n, k = k, n_left = fit$n_left, n_right = fit$n_right, n_uncensored = fit$n_uncensored, censored_share = share,
                         left = left, right = right, sigma = sigma, sigma_se = sigma_se, log_sigma = fit$log_sigma, log_lik = fit$loglik,
                         log_lik_null = null$loglik, lr_chi2 = lr, lr_df = lr_df, lr_p = lr_p, aic = aic, bic = bic,
                         scale_factor = eff$scale, prob_uncensored = eff$prob_uncensored, mm_share = eff$mm_share, converged = fit$converged,
                         iterations = fit$iterations, n_params = k + 1, max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1,
                         missing_share = if (n_input > 0) n_dropped / n_input else 0))
limits <- paste(c(if (!is.null(left)) sprintf("below at %s", sprintf("%g", left)), if (!is.null(right)) sprintf("above at %s", sprintf("%g", right))), collapse = " and ")
significant <- vapply(Filter(function(cf) cf$p < 1 - conf, coefs[-1]), `[[`, "", "term")
summary <- paste0(sprintf("Tobit regression of %s censored %s (n = %d, %d censored): LR χ²(%d) = %.2f, %s; σ = %.3f. ", outcome, limits, n, censored, lr_df, lr, cs_fmt_p(lr_p), sigma),
                  if (length(significant)) sprintf("Significant terms: %s.", paste(significant, collapse = ", ")) else "No individual term is significant.")
pct <- sprintf("%.0f%%", conf * 100)
sl <- coefs[-1]
cs_publish(list(
  method = "regression.censored",
  methodVersion = "1.0.2",
  title = "Censored regression (Tobit)",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("χ²(%d, N = %d) = %.2f, %s, σ = %.2f", lr_df, n, lr, cs_fmt_p(lr_p), sigma),
  statistics = list(list(key = "lr_chi2", label = "LR χ²", value = lr), list(key = "lr_p", label = "p", value = lr_p, format = "p"),
                    list(key = "sigma", label = "σ", value = sigma), list(key = "censored_share", label = "Censored", value = share, format = "percent")),
  tables = list(list(key = "coefficients", title = "Coefficients (latent outcome) and average marginal effects", 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 = "z", label = "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"), list(key = "ame", label = "Effect on E[y]", type = "number")),
    rows = coefs, note = sprintf("B is the effect on the latent (uncensored) outcome; the effect on the observed mean is B × %.3f, the average probability of being uncensored.", eff$scale))),
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Maximum likelihood (Newton–Raphson from OLS, %d iterations); covariance from the observed information; Wald z tests; σ = %.4f (SE by the delta method from log σ).", fit$iterations, sigma)),
  charts = list(cs_chart("coefficients", "forest", "Effects on the latent outcome", 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)),
    # Observed outcome against the fitted latent mean x'b, censored rows marked at their limit (Chart Lab `censored-fit`).
    cs_chart("fit", "censored-fit", "Observed outcome against the fitted latent mean", list(
      fitted = cs_col("Fitted latent mean (x\u2032\u03b2)", as.numeric(X %*% b), kind = "numeric"),
      observed = cs_col(outcome, as.numeric(y), kind = "numeric"),
      status = cs_col("Censoring", ifelse(!is.null(left) & y <= (if (is.null(left)) -Inf else left), "left-censored",
                                   ifelse(!is.null(right) & y >= (if (is.null(right)) Inf else right), "right-censored", "observed")),
                      kind = "categorical")))),
  values = values
))

Sources

  • Tobin, J. (1958). Estimation of relationships for limited dependent variables. Econometrica, 26, 24–36.
  • McDonald, J. F., & Moffitt, R. A. (1980). The uses of Tobit analysis. Review of Economics and Statistics, 62, 318–321.
  • Greene, W. H. (2018). Econometric Analysis (8th ed.), Section 19.3. Pearson.
  • Kleiber, C., & Zeileis, A. (2008). Applied Econometrics with R (AER::tobit). Springer.

From the CodeSplash method registry · regression.censored v1.0.2.