Compare each unit with itself
Use repeated measurements to remove everything constant within a unit, choose between fixed and random effects, and pick standard errors the diagnostics support.
What runs in CodeSplash
- STAT182Hausman specification test Runs in CodeSplash
- STAT223Pesaran CD test Runs in CodeSplash
- STAT224Breusch–Pagan LM test for cross-sectional dependence Runs in CodeSplash
- STAT225Wooldridge test for panel serial correlation Runs in CodeSplash
- Panel data models (fixed effects, random effects, first differences) Verified in Python and R
You will be able to
- Explain what fixed effects remove and what they leave behind
- Read a Hausman test without treating it as a verdict
- Match Pesaran CD, Breusch–Pagan and Wooldridge results to the standard errors they call for
Read first
Two kinds of comparison
ReadThe Grunfeld data follow 10 firms for 20 years, recording investment and market value.
Comparing firms with each other mixes value with everything else that makes one firm unlike another. Fixed effectsFixed effectsA panel model that compares each unit with itself, removing everything constant within a unit, measured or not. compare each firm only with itself, by subtracting its own average:
Anything constant within a firm, measured or not, disappears in that subtraction.
How much does pooling mislead?
PredictPredict first
A panel of US states asks how public capital relates to output, in logs. Pooled OLS treats every state-year as a separate comparison. Compared with pooled OLS, what happens to the estimate when you add state and year fixed effects?
Reveal
Pooled, with one control: 0.756. Two-way fixed effects, with fuller controls: −0.0302, with an interval from −0.127 to 0.0670. The specifications differ, so this isn't a clean decomposition. Still, large states have more of everything, and much of the pooled slope looks like that difference between states.
Run one
In the appb = 0.110, SE = 0.015, t(9) = 7.27, p < .001, 95% CI [0.076, 0.144]
- Coefficient of value
- 0.1101
- 95% CI
- [0.0758, 0.1444]
- p
- < .001
- Units
- 10
- Periods
- 20
- Share of variance between units
- 0.7180
Plots
View data
| estimate | model | high | model | low |
|---|---|---|---|---|
| 0.1101 | This analysis | 0.1444 | Fixed effects (within) | 0.0758 |
| 0.1177 | Other models | 0.1409 | Two-way fixed effects | 0.0945 |
| 0.1098 | Other models | 0.1409 | Random effects (Swamy–Arora) | 0.0787 |
| 0.0898 | Other models | 0.1205 | First differences | 0.0591 |
| 0.1156 | Other models | 0.1515 | Pooled OLS | 0.0796 |
| 0.1346 | Other models | 0.2026 | Between (unit means) | 0.0667 |
View data
| kind | value | inv |
|---|---|---|
| observation | 3078.50 | 317.60 |
| observation | 4661.70 | 391.80 |
| observation | 5387.10 | 410.60 |
| observation | 2792.20 | 257.70 |
| observation | 4313.20 | 330.80 |
| observation | 4643.90 | 461.20 |
| observation | 4551.20 | 512 |
| observation | 3244.10 | 448 |
| observation | 4053.70 | 499.60 |
| observation | 4379.30 | 547.50 |
| observation | 4840.90 | 561.20 |
| observation | 4900.90 | 688.10 |
| observation | 3526.50 | 568.90 |
| observation | 3254.70 | 529.20 |
| observation | 3700.20 | 555.10 |
| observation | 3755.60 | 642.90 |
| observation | 4,833 | 755.90 |
| observation | 4924.90 | 891.20 |
| observation | 6241.70 | 1304.40 |
| observation | 5593.60 | 1486.70 |
| observation | 1362.40 | 209.90 |
| observation | 1807.10 | 355.30 |
| observation | 2676.30 | 469.90 |
| observation | 1801.90 | 262.30 |
| observation | 1957.30 | 230.40 |
| observation | 2202.90 | 361.60 |
| observation | 2380.50 | 472.80 |
| observation | 2168.60 | 445.60 |
| observation | 1985.10 | 361.60 |
| observation | 1813.90 | 288.20 |
| observation | 1850.20 | 258.70 |
| observation | 2067.70 | 420.30 |
| observation | 1796.70 | 420.50 |
| observation | 1625.80 | 494.50 |
| observation | 1,667 | 405.10 |
| observation | 1677.40 | 418.80 |
| observation | 2289.50 | 588.20 |
| observation | 2159.40 | 645.50 |
| observation | 2031.30 | 641 |
| observation | 2115.50 | 459.30 |
| observation | 1170.60 | 33.100 |
| observation | 2015.80 | 45 |
| observation | 2803.30 | 77.200 |
| observation | 2039.70 | 44.600 |
| observation | 2256.20 | 48.100 |
| observation | 2132.20 | 74.400 |
| observation | 1834.10 | 113 |
| observation | 1,588 | 91.900 |
| observation | 1749.40 | 61.300 |
| observation | 1687.20 | 56.800 |
| observation | 2007.70 | 93.600 |
| observation | 2208.30 | 159.90 |
| observation | 1656.70 | 147.20 |
| observation | 1604.40 | 146.30 |
| observation | 1431.80 | 98.300 |
| observation | 1610.50 | 93.500 |
| observation | 1819.40 | 135.20 |
| observation | 2079.70 | 157.30 |
| observation | 2371.60 | 179.50 |
| observation | 2759.90 | 189.60 |
First 60 of 210 rows.
View data
| effect | high | firm | low |
|---|---|---|---|
| −70.297 | 27.129 | 1 | −167.72 |
| 101.91 | 150.78 | 2 | 53.028 |
| −235.57 | −187.69 | 3 | −283.46 |
| −27.809 | −0.2174 | 4 | −55.401 |
| −114.62 | −86.853 | 5 | −142.38 |
| −23.161 | 1.669 | 6 | −47.992 |
| −66.553 | −41.382 | 7 | −91.725 |
| −57.546 | −30.120 | 8 | −84.972 |
| −87.222 | −61.955 | 9 | −112.49 |
| −6.568 | 16.612 | 10 | −29.748 |
View data
| firm | firm | correlation |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | −0.0533 |
| 3 | 1 | −0.2173 |
| 4 | 1 | −0.1912 |
| 5 | 1 | −0.4555 |
| 6 | 1 | −0.2489 |
| 7 | 1 | −0.2234 |
| 8 | 1 | −0.4390 |
| 9 | 1 | −0.3939 |
| 10 | 1 | 0.4196 |
| 1 | 2 | −0.0533 |
| 2 | 2 | 1 |
| 3 | 2 | −0.0935 |
| 4 | 2 | 0.1540 |
| 5 | 2 | −0.3997 |
| 6 | 2 | −0.1310 |
| 7 | 2 | −0.5074 |
| 8 | 2 | −0.1120 |
| 9 | 2 | −0.3290 |
| 10 | 2 | 0.3937 |
| 1 | 3 | −0.2173 |
| 2 | 3 | −0.0935 |
| 3 | 3 | 1 |
| 4 | 3 | 0.2084 |
| 5 | 3 | 0.6075 |
| 6 | 3 | 0.6277 |
| 7 | 3 | 0.5516 |
| 8 | 3 | 0.8832 |
| 9 | 3 | 0.7952 |
| 10 | 3 | −0.1534 |
| 1 | 4 | −0.1912 |
| 2 | 4 | 0.1540 |
| 3 | 4 | 0.2084 |
| 4 | 4 | 1 |
| 5 | 4 | 0.0490 |
| 6 | 4 | 0.1334 |
| 7 | 4 | 0.0291 |
| 8 | 4 | 0.2432 |
| 9 | 4 | 0.0675 |
| 10 | 4 | −0.0030 |
| 1 | 5 | −0.4555 |
| 2 | 5 | −0.3997 |
| 3 | 5 | 0.6075 |
| 4 | 5 | 0.0490 |
| 5 | 5 | 1 |
| 6 | 5 | 0.8320 |
| 7 | 5 | 0.9318 |
| 8 | 5 | 0.8081 |
| 9 | 5 | 0.8772 |
| 10 | 5 | −0.6206 |
| 1 | 6 | −0.2489 |
| 2 | 6 | −0.1310 |
| 3 | 6 | 0.6277 |
| 4 | 6 | 0.1334 |
| 5 | 6 | 0.8320 |
| 6 | 6 | 1 |
| 7 | 6 | 0.7896 |
| 8 | 6 | 0.7542 |
| 9 | 6 | 0.7229 |
| 10 | 6 | −0.3208 |
First 60 of 100 rows.
Assumptions
- Fixed or random effects — Hausman p = .312, Mundlak (cluster-robust) p = .233: random effects would also be consistent here and more precise; fixed effects stay safe.
- One slope for all units — Poolability test p < .001: slopes differ across units, so the coefficient is an average of them with weights that favor units whose treatment moves most.
- Treatment changes within units — 6.7% of the variation in value is within units.
- No feedback to later treatment — Next period's value does not predict today's outcome (p = .938): compatible with strict exogeneity.
- Errors across units — Pesaran CD p < .001, mean |ρ| 0.44: errors move together across units, so these standard errors are too small. Use Driscoll–Kraay standard errors.
- Errors over time — Wooldridge test p < .001: errors are correlated over time; the chosen standard errors allow for it.
- Enough clusters — Only 10 units: clustered standard errors are unreliable below about 30 clusters. Consider a wild cluster bootstrap outside the app, and read the interval cautiously.
Fixed effects (within), clustered by unit standard errors
| Term | Estimate | SE | t | p | Low | High |
|---|---|---|---|---|---|---|
| value | 0.1101 | 0.0152 | 7.266 | 4.734e-5 | 0.0758 | 0.1444 |
| capital | 0.3101 | 0.0526 | 5.893 | 0.0002 | 0.1910 | 0.4291 |
The coefficient of value under each model
| Model | Estimate | SE | Low | High | p |
|---|---|---|---|---|---|
| Fixed effects (within) | 0.1101 | 0.0152 | 0.0758 | 0.1444 | 4.734e-5 |
| Two-way fixed effects | 0.1177 | 0.0103 | 0.0945 | 0.1409 | 1.131e-6 |
| Random effects (Swamy–Arora) | 0.1098 | 0.0138 | 0.0787 | 0.1409 | 2.256e-5 |
| First differences | 0.0898 | 0.0136 | 0.0591 | 0.1205 | 9.794e-5 |
| Pooled OLS | 0.1156 | 0.0159 | 0.0796 | 0.1515 | 4.711e-5 |
| Between (unit means) | 0.1346 | 0.0287 | 0.0667 | 0.2026 | 0.0023 |
Specification tests
| Test | Statistic | df | p | A small p suggests |
|---|---|---|---|---|
| Hausman | 2.330 | 2 | 0.3119 | Random effects are biased: unit differences relate to the regressors |
| Mundlak (cluster-robust) | 1.722 | 2, 9 | 0.2327 | The same question as Hausman, robust to clustering |
| Breusch–Pagan LM, unit effects | 798.16 | 1 | 1.354e-175 | Unit effects exist (random effects rather than pooled) |
| Honda, unit effects | 28.252 | 6.772e-176 | The same, one-sided: a variance can't be negative | |
| King–Wu, unit and period effects | 21.832 | 5.737e-106 | Unit or period effects, one-sided | |
| F test, unit effects | 49.177 | 9, 188 | 8.700e-45 | Fixed effects fit better than pooled OLS |
| F test, period effects | 1.403 | 19, 169 | 0.1309 | Two-way fixed effects fit better than one-way |
| Poolability of slopes | 5.780 | 18, 170 | 1.219e-10 | Slopes differ across units |
| Pesaran CD | 4.661 | 3.144e-6 | Errors move together across units | |
| Breusch–Pagan LM, cross-section | 246.33 | 45 | 1.449e-29 | The same, for few units and many periods |
| Wooldridge, fixed effects | 68.869 | 1, 9 | 1.649e-5 | Errors are correlated over time |
| Wooldridge, first differences | 332.83 | 1, 9 | 2.039e-8 | The same, on differenced errors |
| Lead of the treatment | 0.0802 | 0.9378 | Outcomes feed into later treatment |
- Standard errors clustered by unit; t statistics use 9 degrees of freedom.
The exact R script · R R version 4.5.1 (2025-06-13)
# Panel data models (fixed effects, random effects, first differences)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.panel 1.0.4 · spec 5a6f2231bc56035c
# Dataset: panel_grunfeld (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/panel_grunfeld.parquet", col_select = c("inv", "value", "firm", "year", "capital")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("inv", "value", "firm", "year", "capital")]), , 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("inv", "value", "firm", "year", "capital")) # infinite values stop the run (registry/errors.yaml)
# %% Panel: rows sorted by unit and time, with integer ids
Y <- "inv"
TREAT <- "value"
UNIT <- "firm"
TIME <- "year"
COVARIATES <- c("capital")
UNIT_NUMERIC <- TRUE
TEMPORAL <- FALSE
MODEL <- "fe"
SE <- "cluster_unit"
LAG <- NULL
conf <- 0.95
# A numeric column as is; a two-level column as 0/1 (1 = the chosen level).
as_number <- function(col, chosen = NULL) {
s <- df[[col]]
if (is.factor(s)) {
levels_s <- levels(s)
level <- if (!is.null(chosen)) chosen else if ("true" %in% levels_s) "true" else levels_s[length(levels_s)]
return(list(values = as.numeric(as.character(s) == level), level = level))
}
list(values = as.numeric(s), level = NULL)
}
if (is.factor(df[[TREAT]]) && nlevels(df[[TREAT]]) != 2L) stop(sprintf("%s has %d levels. A treatment must be numeric or have exactly two levels.", TREAT, nlevels(df[[TREAT]])))
tr <- as_number(TREAT, NULL)
treated_level <- tr$level
X <- do.call(cbind, c(list(tr$values), lapply(COVARIATES, function(c) as_number(c)$values)))
names_x <- c(TREAT, COVARIATES)
y <- as.numeric(df[[Y]])
unit_raw <- if (UNIT_NUMERIC) as.numeric(df[[UNIT]]) else as.character(df[[UNIT]])
unit_values <- sort(unique(unit_raw), method = "radix")
uid <- match(unit_raw, unit_values)
time_raw <- if (TEMPORAL) as.numeric(as.Date(df[[TIME]])) else as.numeric(df[[TIME]])
time_values <- sort(unique(time_raw))
tid <- match(time_raw, time_values)
N <- length(unit_values); T_ <- length(time_values)
if (N < 2L) cs_error("CS_E_TOO_FEW_GROUPS", column = UNIT, min = 2, k = N)
if (T_ < 2L) cs_error("CS_E_TOO_FEW_GROUPS", column = TIME, min = 2, k = T_)
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = Y)
ord <- order(uid, tid)
y <- y[ord]; X <- X[ord, , drop = FALSE]; uid <- uid[ord]; tid <- tid[ord]
if (any(uid[-1L] == uid[-length(uid)] & tid[-1L] == tid[-length(tid)])) stop(sprintf("Each unit must have one row per period; %s and %s repeat. Aggregate first.", UNIT, TIME))
unit_labels <- if (UNIT_NUMERIC) vapply(unit_values, function(v) if (v == round(v)) sprintf("%d", as.integer(v)) else as.character(v), "") else unit_values
# %% Which regressors change within units
within <- codesplashr:::.cs_pn_demean(X, uid, N)
sizes <- sqrt(colSums(X * X))
varying <- codesplashr:::.cs_pn_independent(within, sizes)$keep
total_ss <- sum((X[, 1L] - mean(X[, 1L]))^2)
if (total_ss == 0) cs_error("CS_E_CONSTANT", column = TREAT)
within_share <- sum(within[, 1L]^2) / total_ss
absorbing <- MODEL %in% c("fe", "twfe", "fd")
if (absorbing && !(1L %in% varying)) stop(sprintf("%s does not change within units, so this model removes it. Choose random effects or between, or a design for a treatment fixed at the unit level.", TREAT))
# %% Fit
fit <- cs_panel_fit(MODEL, y, X, uid, tid, names_x, SE, LAG)
if (!(TREAT %in% fit$terms)) stop(sprintf("%s cannot be separated from the fixed effects in this model (it may move only with time).", TREAT))
if (length(fit$dropped)) warnings <- c(warnings, paste0("Removed by the model (constant within units or collinear): ", paste(fit$dropped, collapse = ", "), "."))
coefs <- cs_panel_coef_table(fit, conf)
main <- coefs[coefs$term == TREAT, ]
est <- main$estimate; se <- main$se; t_stat <- main$t; p_value <- main$p; ci_low <- main$low; ci_high <- main$high
# %% Specification tests (on the regressors that change within units)
Xw <- X[, varying, drop = FALSE]; names_w <- names_x[varying]
diag <- if (length(varying)) cs_panel_diagnostics(y, Xw, uid, tid, names_w) else list(n_units = N, n_periods = T_, balanced = codesplashr:::.cs_pn_balanced(uid, tid))
rho_matrix <- diag$.rho_matrix
diag$.rho_matrix <- NULL
strict <- if (length(varying) && varying[1L] == 1L) cs_panel_strict_exogeneity(y, Xw, uid, tid, 1L) else NULL
if (!is.null(strict)) { diag$strict_exog_estimate <- strict$estimate; diag$strict_exog_t <- strict$t; diag$strict_exog_p <- strict$p }
# %% The same treatment coefficient under every model
MODEL_LABELS <- c(fe = "Fixed effects (within)", twfe = "Two-way fixed effects", re = "Random effects (Swamy–Arora)", fd = "First differences", pooled = "Pooled OLS", between = "Between (unit means)")
SE_LABELS <- c(classical = "classical", cluster_unit = "clustered by unit", cluster_twoway = "clustered by unit and period", driscoll_kraay = "Driscoll–Kraay", newey_west = "Newey–West within unit")
compare_rows <- list()
for (m in names(MODEL_LABELS)) {
f2 <- if (m == MODEL) fit else tryCatch(cs_panel_fit(m, y, X, uid, tid, names_x, SE, LAG), error = function(e) NULL)
if (is.null(f2) || !(TREAT %in% f2$terms)) next
tb <- cs_panel_coef_table(f2, conf)
r <- tb[tb$term == TREAT, ]
compare_rows[[length(compare_rows) + 1L]] <- list(model = m, label = unname(MODEL_LABELS[m]), estimate = r$estimate, se = r$se, low = r$low, high = r$high, p = r$p, chosen = m == MODEL)
}
# %% Checks: what the tests say about this model and these standard errors
checks <- list()
add_check <- function(id, label, status, detail, downgrade = NULL, fix = NULL) {
c_ <- list(id = id, label = label, status = status, detail = detail)
if (!is.null(downgrade)) c_$downgrade_to <- downgrade
if (!is.null(fix)) c_$fix <- fix
checks[[length(checks) + 1L]] <<- c_
}
pct1 <- function(v) sprintf("%.1f%%", 100 * v)
hp <- diag$hausman_p; mp <- diag$mundlak_p
# The Mundlak row decides when there is one: it holds near 5%, while Hausman reaches 8–15% in short panels whose regressors vary little between units.
effects_reject <- if (!is.null(mp)) mp < 0.05 else (!is.null(hp) && hp < 0.05)
if (!is.null(hp) || !is.null(mp)) {
parts <- character(0)
if (!is.null(hp)) parts <- c(parts, sprintf("Hausman %s", cs_fmt_p(hp)))
if (!is.null(mp)) parts <- c(parts, sprintf("Mundlak (cluster-robust) %s", cs_fmt_p(mp)))
reading <- paste(parts, collapse = ", ")
if (isFALSE(diag$hausman_full_rank)) reading <- paste0(reading, "; the Hausman difference matrix is not positive definite, so trust the Mundlak row")
if (isTRUE(diag$hausman_full_rank) && !is.null(hp) && !is.null(mp) && hp < 0.05 && mp >= 0.05) reading <- paste0(reading, "; Hausman runs high in short panels, so trust the Mundlak row")
use_fe <- list(label = "Use fixed effects", options = list(model = "fe"))
if (MODEL == "re" && effects_reject) {
add_check("hausman", "Fixed or random effects", "concern", sprintf("%s: unit differences are related to the regressors, so random effects are biased. Use fixed effects.", reading), "L1", use_fe)
} else if (MODEL == "re") {
add_check("hausman", "Fixed or random effects", "pass", sprintf("%s: no sign that unit differences are related to the regressors; random effects are defensible and more precise.", reading))
} else if (MODEL %in% c("pooled", "between") && effects_reject) {
add_check("hausman", "Fixed or random effects", "concern", sprintf("%s: unit differences are related to the regressors, so this model is biased. Use fixed effects.", reading), "L1", use_fe)
} else if (effects_reject) {
add_check("hausman", "Fixed or random effects", "pass", sprintf("%s: unit differences are related to the regressors, which is why fixed effects are needed.", reading))
} else {
add_check("hausman", "Fixed or random effects", "info", sprintf("%s: random effects would also be consistent here and more precise; fixed effects stay safe.", reading))
}
}
fu <- diag$f_unit_p
if (MODEL == "pooled" && !is.null(fu) && fu < 0.05) add_check("poolability", "Pooling units", "concern", sprintf("The F test of unit effects %s: units differ, so pooled OLS mixes within and between differences. Use fixed effects.", cs_fmt_p(fu)), "L1", list(label = "Use fixed effects", options = list(model = "fe")))
pl <- diag$poolability_p
if (!is.null(pl) && pl < 0.05 && MODEL %in% c("fe", "twfe", "fd", "re")) add_check("poolability", "One slope for all units", "info", sprintf("Poolability test %s: slopes differ across units, so the coefficient is an average of them with weights that favor units whose treatment moves most.", cs_fmt_p(pl)))
if (within_share < 0.05 && absorbing) {
add_check("within_variation", "Treatment changes within units", "concern", sprintf("Only %s of the variation in %s is within units; the estimate rests on little change and is noisy.", pct1(within_share), TREAT))
} else if (absorbing) {
add_check("within_variation", "Treatment changes within units", "pass", sprintf("%s of the variation in %s is within units.", pct1(within_share), TREAT))
}
if (!is.null(strict)) {
if (strict$p < 0.05) {
add_check("strict_exog", "No feedback to later treatment", "concern", sprintf("Next period's %s predicts today's outcome (%s): outcomes may drive later treatment, which biases fixed effects.", TREAT, cs_fmt_p(strict$p)), "L1")
} else {
add_check("strict_exog", "No feedback to later treatment", "pass", sprintf("Next period's %s does not predict today's outcome (%s): compatible with strict exogeneity.", TREAT, cs_fmt_p(strict$p)))
}
}
cd_p <- diag$cd_p
if (!is.null(cd_p)) {
robust_cd <- fit$se %in% c("driscoll_kraay", "cluster_twoway")
long_enough <- T_ >= 20L
if (cd_p < 0.05 && !robust_cd) {
fix <- if (long_enough) list(label = "Use Driscoll–Kraay standard errors", options = list(se = "driscoll_kraay")) else list(label = "Cluster by unit and period", options = list(se = "cluster_twoway"))
add_check("cross_section", "Errors across units", "concern", sprintf("Pesaran CD %s, mean |ρ| %.2f: errors move together across units, so these standard errors are too small. %s.", cs_fmt_p(cd_p), diag$rho_abs_mean, fix$label), NULL, fix)
} else if (cd_p < 0.05) {
add_check("cross_section", "Errors across units", "pass", sprintf("Pesaran CD %s, mean |ρ| %.2f: errors move together across units; the chosen standard errors allow for it.", cs_fmt_p(cd_p), diag$rho_abs_mean))
} else {
add_check("cross_section", "Errors across units", "pass", sprintf("Pesaran CD %s: no sign that errors move together across units.", cs_fmt_p(cd_p)))
}
}
wp <- diag$wooldridge_p
if (!is.null(wp)) {
if (wp < 0.05 && fit$se == "classical") {
add_check("serial_correlation", "Errors over time", "concern", sprintf("Wooldridge test %s: errors are correlated over time, so classical standard errors are too small. Cluster by unit.", cs_fmt_p(wp)), NULL, list(label = "Cluster by unit", options = list(se = "cluster_unit")))
} else if (wp < 0.05) {
add_check("serial_correlation", "Errors over time", "pass", sprintf("Wooldridge test %s: errors are correlated over time; the chosen standard errors allow for it.", cs_fmt_p(wp)))
} else {
add_check("serial_correlation", "Errors over time", "pass", sprintf("Wooldridge test %s: no sign of serial correlation in the errors.", cs_fmt_p(wp)))
}
}
if (fit$se %in% c("cluster_unit", "cluster_twoway") && N < 30L) add_check("clusters", "Enough clusters", "concern", sprintf("Only %d units: clustered standard errors are unreliable below about 30 clusters. Consider a wild cluster bootstrap outside the app, and read the interval cautiously.", N))
if (fit$se == "driscoll_kraay" && T_ < 50L) add_check("clusters", "Enough periods", "concern", sprintf("Only %d periods: Driscoll–Kraay tests reject too often on short panels, about 12%% at 10 periods, 9%% at 20 and 8%% at 40 at the 5%% level in simulations with no effect. Aim for 50 or more.", T_))
if (isTRUE(diag$re_negative_variance) && MODEL == "re") add_check("re_variance", "Random effects variance", "info", "The estimated unit variance came out negative, so it was set to 0 and random effects equal pooled OLS.")
# %% Result
level_note <- if (!is.null(treated_level)) sprintf(" being %s", treated_level) else ""
MODEL_LABEL <- unname(MODEL_LABELS[MODEL])
n <- length(y)
claim <- c(fe = "L2", twfe = "L2", fd = "L2", re = "L2", pooled = "L1", between = "L1")[[MODEL]]
keys <- c("sigma_e", "sigma_u", "rho_icc", "theta_mean", "re_negative_variance", "hausman_stat", "hausman_df", "hausman_p", "hausman_full_rank", "mundlak_f", "mundlak_df1", "mundlak_df2", "mundlak_p",
"bp_lm_stat", "bp_lm_p", "honda_z", "honda_p", "bp_time_stat", "bp_time_p", "bp_twoway_stat", "bp_twoway_p", "honda_twoway_z", "honda_twoway_p", "king_wu_z", "king_wu_p",
"f_unit_stat", "f_unit_df1", "f_unit_df2", "f_unit_p", "f_time_stat", "f_time_df1", "f_time_df2", "f_time_p", "poolability_stat", "poolability_df1", "poolability_df2", "poolability_p",
"cd_stat", "cd_p", "cd_lm_stat", "cd_lm_df", "cd_lm_p", "cd_sclm_stat", "cd_sclm_p", "cd_pairs", "rho_mean", "rho_abs_mean",
"wooldridge_stat", "wooldridge_df1", "wooldridge_df2", "wooldridge_p", "wooldridge_rho", "wooldridge_fd_stat", "wooldridge_fd_df2", "wooldridge_fd_p", "wooldridge_fd_rho",
"strict_exog_estimate", "strict_exog_t", "strict_exog_p")
values <- list(
estimate = est, se = se, t = t_stat, p_value = p_value, ci_low = ci_low, ci_high = ci_high, df_t = fit$df_t, n = n, n_units = N, n_periods = T_,
balanced = isTRUE(diag$balanced), model = MODEL, model_label = tolower(MODEL_LABEL), se_type = fit$se, lag = fit$lag, r2 = fit$r2, within_share = within_share
)
for (k in keys) values[k] <- list(diag[[k]])
values$estimand <- if (absorbing) "Average within-unit effect" else if (MODEL == "re") "Average effect, assuming unit differences are unrelated to treatment" else "Association across units"
values$effect_label <- sprintf("Change in %s per unit of %s%s", Y, TREAT, level_note)
values$claim_level_max <- claim
for (c_ in checks) values[[sprintf("check[%s]", c_$id)]] <- c_$status
diag_rows <- list()
add_row <- function(key, test, stat, dof, p, looks_for) {
if (!is.null(stat)) diag_rows[[length(diag_rows) + 1L]] <<- list(test = test, statistic = stat, df = dof, p = if (is.null(p)) NA_real_ else p, looks_for = looks_for)
}
dof2 <- function(a, b) if (!is.null(diag[[a]])) sprintf("%d, %d", as.integer(diag[[a]]), as.integer(diag[[b]])) else ""
add_row("hausman", "Hausman", diag$hausman_stat, if (!is.null(diag$hausman_df)) sprintf("%d", as.integer(diag$hausman_df)) else "", hp, "Random effects are biased: unit differences relate to the regressors")
add_row("mundlak", "Mundlak (cluster-robust)", diag$mundlak_f, dof2("mundlak_df1", "mundlak_df2"), mp, "The same question as Hausman, robust to clustering")
add_row("bp_lm", "Breusch–Pagan LM, unit effects", diag$bp_lm_stat, "1", diag$bp_lm_p, "Unit effects exist (random effects rather than pooled)")
add_row("honda", "Honda, unit effects", diag$honda_z, "", diag$honda_p, "The same, one-sided: a variance can't be negative")
add_row("king_wu", "King–Wu, unit and period effects", diag$king_wu_z, "", diag$king_wu_p, "Unit or period effects, one-sided")
add_row("f_unit", "F test, unit effects", diag$f_unit_stat, dof2("f_unit_df1", "f_unit_df2"), fu, "Fixed effects fit better than pooled OLS")
add_row("f_time", "F test, period effects", diag$f_time_stat, dof2("f_time_df1", "f_time_df2"), diag$f_time_p, "Two-way fixed effects fit better than one-way")
add_row("poolability", "Poolability of slopes", diag$poolability_stat, dof2("poolability_df1", "poolability_df2"), pl, "Slopes differ across units")
add_row("cd", "Pesaran CD", diag$cd_stat, "", cd_p, "Errors move together across units")
add_row("cd_lm", "Breusch–Pagan LM, cross-section", diag$cd_lm_stat, if (!is.null(diag$cd_lm_df)) sprintf("%d", as.integer(diag$cd_lm_df)) else "", diag$cd_lm_p, "The same, for few units and many periods")
add_row("wooldridge", "Wooldridge, fixed effects", diag$wooldridge_stat, dof2("wooldridge_df1", "wooldridge_df2"), wp, "Errors are correlated over time")
add_row("wooldridge_fd", "Wooldridge, first differences", diag$wooldridge_fd_stat, if (!is.null(diag$wooldridge_fd_df2)) sprintf("1, %d", as.integer(diag$wooldridge_fd_df2)) else "", diag$wooldridge_fd_p, "The same, on differenced errors")
add_row("strict_exog", "Lead of the treatment", diag$strict_exog_t, "", diag$strict_exog_p, "Outcomes feed into later treatment")
cmp <- function(k) vapply(compare_rows, function(r) r[[k]], if (k %in% c("label", "model")) "" else 0)
charts <- list(cs_chart("compare", "forest", sprintf("Coefficient of %s under each model", TREAT), list(
label = cs_col("model", cmp("label"), kind = "categorical"),
estimate = cs_col("estimate", cmp("estimate")),
low = cs_col("low", cmp("low")),
high = cs_col("high", cmp("high")),
group = cs_col("model", ifelse(vapply(compare_rows, function(r) r$chosen, TRUE), "This analysis", "Other models"), kind = "categorical", levels = c("This analysis", "Other models"))
)))
# Within vs between: the slope of the outcome on the treatment alone, three ways.
x0 <- X[, 1L]
one_x <- matrix(x0, ncol = 1L)
slope_of <- function(m) {
f1 <- cs_panel_fit(m, y, one_x, uid, tid, TREAT, "classical")
f1$b[match(TREAT, f1$terms)]
}
stride <- max(1L, as.integer(ceiling(n / 2000)))
pick <- seq(1L, n, by = stride)
means_x <- codesplashr:::.cs_pn_group_mean(x0, uid, N)
means_y <- codesplashr:::.cs_pn_group_mean(y, uid, N)
charts[[length(charts) + 1L]] <- cs_chart("within_between", "within-between", sprintf("%s and %s: within and between units", Y, TREAT), list(
x = cs_col(TREAT, c(x0[pick], means_x)),
y = cs_col(Y, c(y[pick], means_y)),
kind = cs_col("kind", c(rep("observation", length(pick)), rep("unit mean", N)), kind = "categorical", levels = c("observation", "unit mean"))
), controls = list(withinSlope = if (1L %in% varying) slope_of("fe") else NULL, betweenSlope = slope_of("between"), pooledSlope = slope_of("pooled"), xMean = mean(x0), yMean = mean(y)))
if (MODEL %in% c("fe", "twfe")) {
fe_fit <- cs_panel_fit("fe", y, X, uid, tid, names_x, "classical")
ue <- cs_panel_unit_effects(fe_fit, y, X, uid, names_x)
keep_units <- sort(order(-abs(ue$effect - ue$mean))[seq_len(min(40L, N))])
z <- qnorm(0.5 + conf / 2)
charts[[length(charts) + 1L]] <- cs_chart("unit_effects", "unit-effects", "Unit fixed effects", list(
label = cs_col(UNIT, unit_labels[keep_units], kind = "categorical"),
effect = cs_col("effect", ue$effect[keep_units]),
low = cs_col("low", ue$effect[keep_units] - z * ue$se[keep_units]),
high = cs_col("high", ue$effect[keep_units] + z * ue$se[keep_units])
), controls = list(reference = ue$mean), note = if (N > 40L) sprintf("The 40 units furthest from the mean, of %d.", N) else NULL)
}
if (!is.null(rho_matrix) && N <= 30L) {
cells <- expand.grid(j = seq_len(N), i = seq_len(N))
vals_h <- as.numeric(t(rho_matrix))
vals_h[!is.finite(vals_h)] <- NA
charts[[length(charts) + 1L]] <- cs_chart("residual_correlation", "matrix-heatmap", "Residual correlations between units", list(
row = cs_col(UNIT, unit_labels[cells$i], kind = "categorical", levels = unit_labels),
col = cs_col(UNIT, unit_labels[cells$j], kind = "categorical", levels = unit_labels),
value = cs_col("correlation", vals_h, kind = "numeric")
))
}
se_label <- unname(SE_LABELS[fit$se])
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("With %s and %s standard errors, a one-unit change in %s%s goes with a change of %.3f in %s (%s CI [%.3f, %.3f], %s), across %d units and %d periods.",
tolower(MODEL_LABEL), se_label, TREAT, level_note, est, Y, pct, ci_low, ci_high, cs_fmt_p(p_value), N, T_)
concerns <- Filter(function(c_) c_$status == "concern", checks)
if (length(concerns)) summary <- paste(summary, concerns[[1]]$detail)
notes <- list(sprintf("Standard errors %s%s; t statistics use %d degrees of freedom.", se_label, if (!is.null(fit$lag)) sprintf(" (lag %d)", fit$lag) else "", as.integer(fit$df_t)))
if (!isTRUE(diag$balanced)) notes <- c(notes, sprintf("The panel is unbalanced: %d rows of a possible %d.", n, N * T_))
if (MODEL == "between" && SE != "classical") notes <- c(notes, "The between model has one row per unit, so its standard errors are classical.")
status_map <- c(concern = "warn", fail = "fail", pass = "pass", info = "info")
cs_publish(list(
method = "causal.panel",
methodVersion = "1.0.4",
title = "Panel data model",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("b = %s, SE = %s, t(%d) = %.2f, %s, %s CI [%.3f, %.3f]", cs_fmt_num(est, 3), cs_fmt_num(se, 3), as.integer(fit$df_t), t_stat, cs_fmt_p(p_value), pct, ci_low, ci_high),
statistics = list(
list(key = "estimate", label = sprintf("Coefficient of %s", TREAT), value = est),
list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high)),
list(key = "p_value", label = "p", value = p_value, format = "p"),
list(key = "n_units", label = "Units", value = N, format = "int"),
list(key = "n_periods", label = "Periods", value = T_, format = "int"),
list(key = "rho_icc", label = "Share of variance between units", value = diag$rho_icc)
),
tables = list(
list(key = "coefficients", title = sprintf("%s, %s standard errors", MODEL_LABEL, se_label),
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"),
list(key = "p", label = "p", type = "p"), list(key = "low", label = "Low", type = "number"), list(key = "high", label = "High", type = "number")),
rows = coefs),
list(key = "compare", title = sprintf("The coefficient of %s under each model", TREAT),
columns = list(list(key = "label", label = "Model", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "low", label = "Low", type = "number"),
list(key = "high", label = "High", type = "number"), list(key = "p", label = "p", type = "p")),
rows = data.frame(label = cmp("label"), estimate = cmp("estimate"), se = cmp("se"), low = cmp("low"), high = cmp("high"), p = cmp("p"), stringsAsFactors = FALSE)),
list(key = "diagnostics", title = "Specification tests",
columns = list(list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
list(key = "df", label = "df", type = "string"), list(key = "p", label = "p", type = "p"),
list(key = "looks_for", label = "A small p suggests", type = "string")),
rows = do.call(rbind, lapply(diag_rows, as.data.frame, stringsAsFactors = FALSE)))
),
assumptions = lapply(checks, function(c_) list(key = c_$id, label = c_$label, status = unname(status_map[c_$status]), detail = c_$detail)),
checks = checks,
warnings = warnings,
notes = notes,
values = values,
charts = charts
))
b = 0.110, SE = 0.015, t(9) = 7.27, p < .001, 95% CI [0.076, 0.144]
- Coefficient of value
- 0.1101
- 95% CI
- [0.0758, 0.1444]
- p
- < .001
- Units
- 10
- Periods
- 20
- Share of variance between units
- 0.7180
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Fixed or random effects — Hausman p = .312, Mundlak (cluster-robust) p = .233: random effects would also be consistent here and more precise; fixed effects stay safe.
- One slope for all units — Poolability test p < .001: slopes differ across units, so the coefficient is an average of them with weights that favor units whose treatment moves most.
- Treatment changes within units — 6.7% of the variation in value is within units.
- No feedback to later treatment — Next period's value does not predict today's outcome (p = .938): compatible with strict exogeneity.
- Errors across units — Pesaran CD p < .001, mean |ρ| 0.44: errors move together across units, so these standard errors are too small. Use Driscoll–Kraay standard errors.
- Errors over time — Wooldridge test p < .001: errors are correlated over time; the chosen standard errors allow for it.
- Enough clusters — Only 10 units: clustered standard errors are unreliable below about 30 clusters. Consider a wild cluster bootstrap outside the app, and read the interval cautiously.
Fixed effects (within), clustered by unit standard errors
| Term | Estimate | SE | t | p | Low | High |
|---|---|---|---|---|---|---|
| value | 0.1101 | 0.0152 | 7.266 | 4.734e-5 | 0.0758 | 0.1444 |
| capital | 0.3101 | 0.0526 | 5.893 | 0.0002 | 0.1910 | 0.4291 |
The coefficient of value under each model
| Model | Estimate | SE | Low | High | p |
|---|---|---|---|---|---|
| Fixed effects (within) | 0.1101 | 0.0152 | 0.0758 | 0.1444 | 4.734e-5 |
| Two-way fixed effects | 0.1177 | 0.0103 | 0.0945 | 0.1409 | 1.131e-6 |
| Random effects (Swamy–Arora) | 0.1098 | 0.0138 | 0.0787 | 0.1409 | 2.256e-5 |
| First differences | 0.0898 | 0.0136 | 0.0591 | 0.1205 | 9.794e-5 |
| Pooled OLS | 0.1156 | 0.0159 | 0.0796 | 0.1515 | 4.711e-5 |
| Between (unit means) | 0.1346 | 0.0287 | 0.0667 | 0.2026 | 0.0023 |
Specification tests
| Test | Statistic | df | p | A small p suggests |
|---|---|---|---|---|
| Hausman | 2.330 | 2 | 0.3119 | Random effects are biased: unit differences relate to the regressors |
| Mundlak (cluster-robust) | 1.722 | 2, 9 | 0.2327 | The same question as Hausman, robust to clustering |
| Breusch–Pagan LM, unit effects | 798.16 | 1 | 1.354e-175 | Unit effects exist (random effects rather than pooled) |
| Honda, unit effects | 28.252 | 6.772e-176 | The same, one-sided: a variance can't be negative | |
| King–Wu, unit and period effects | 21.832 | 5.737e-106 | Unit or period effects, one-sided | |
| F test, unit effects | 49.177 | 9, 188 | 8.700e-45 | Fixed effects fit better than pooled OLS |
| F test, period effects | 1.403 | 19, 169 | 0.1309 | Two-way fixed effects fit better than one-way |
| Poolability of slopes | 5.780 | 18, 170 | 1.219e-10 | Slopes differ across units |
| Pesaran CD | 4.661 | 3.144e-6 | Errors move together across units | |
| Breusch–Pagan LM, cross-section | 246.33 | 45 | 1.449e-29 | The same, for few units and many periods |
| Wooldridge, fixed effects | 68.869 | 1, 9 | 1.649e-5 | Errors are correlated over time |
| Wooldridge, first differences | 332.83 | 1, 9 | 2.039e-8 | The same, on differenced errors |
| Lead of the treatment | 0.0802 | 0.9378 | Outcomes feed into later treatment |
- Standard errors clustered by unit; t statistics use 9 degrees of freedom.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Panel data models (fixed effects, random effects, first differences)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.panel 1.0.4 · spec 5a6f2231bc56035c
# Dataset: panel_grunfeld (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
import codesplash as cs
from codesplash.causal import panel as pn
# %% Data
df = pd.read_parquet("tests/parity/fixtures/panel_grunfeld.parquet", columns=["inv", "value", "firm", "year", "capital"])
n_input = len(df)
df = df.dropna(subset=["inv", "value", "firm", "year", "capital"]) # 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, ["inv", "value", "firm", "year", "capital"]) # infinite values stop the run (registry/errors.yaml)
# %% Panel: rows sorted by unit and time, with integer ids
Y, TREAT, UNIT, TIME = "inv", "value", "firm", "year"
COVARIATES = ["capital"]
UNIT_NUMERIC = True
TEMPORAL = False
MODEL, SE = "fe", "cluster_unit"
LAG = None
conf = 0.95
def as_number(col, chosen=None):
"""A numeric column as is; a two-level column as 0/1 (1 = the chosen level)."""
s = df[col]
if isinstance(s.dtype, pd.CategoricalDtype):
levels = [str(x) for x in s.cat.categories]
level = chosen if chosen is not None else ("true" if "true" in levels else levels[-1])
return (s.astype(str) == level).astype(float).to_numpy(), level
return s.astype(float).to_numpy(), None
if isinstance(df[TREAT].dtype, pd.CategoricalDtype) and len(df[TREAT].cat.categories) != 2:
raise ValueError(f"{TREAT} has {len(df[TREAT].cat.categories)} levels. A treatment must be numeric or have exactly two levels.")
treatment, treated_level = as_number(TREAT, None)
X = np.column_stack([treatment] + [as_number(c)[0] for c in COVARIATES])
names = [TREAT] + COVARIATES
y = df[Y].astype(float).to_numpy()
unit_values, uid = np.unique(df[UNIT].astype(float).to_numpy() if UNIT_NUMERIC else df[UNIT].astype(str).to_numpy(), return_inverse=True)
time_values, tid = np.unique(pd.to_datetime(df[TIME]).to_numpy() if TEMPORAL else df[TIME].astype(float).to_numpy(), return_inverse=True)
N, T = len(unit_values), len(time_values)
if N < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=UNIT, min=2, k=N)
if T < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=TIME, min=2, k=T)
if np.unique(y).size < 2:
cs.cs_error("CS_E_CONSTANT", column=Y)
order = np.lexsort((tid, uid))
y, X, uid, tid = y[order], X[order], uid[order], tid[order]
if np.any((uid[1:] == uid[:-1]) & (tid[1:] == tid[:-1])):
raise ValueError(f"Each unit must have one row per period; {UNIT} and {TIME} repeat. Aggregate first.")
unit_labels = [str(int(v)) if UNIT_NUMERIC and float(v).is_integer() else str(v) for v in unit_values]
# %% Which regressors change within units
within = pn.demean(X, uid, N)
sizes = np.sqrt(np.sum(X * X, axis=0))
varying, _ = pn.independent(within, sizes)
total_ss = np.sum((X[:, 0] - X[:, 0].mean()) ** 2)
within_share = float(np.sum(within[:, 0] ** 2) / total_ss) if total_ss > 0 else 0.0
if total_ss == 0:
cs.cs_error("CS_E_CONSTANT", column=TREAT)
absorbing = MODEL in ("fe", "twfe", "fd")
if absorbing and 0 not in varying:
raise ValueError(f"{TREAT} does not change within units, so this model removes it. Choose random effects or between, or a design for a treatment fixed at the unit level.")
# %% Fit
fit = pn.fit(MODEL, y, X, uid, tid, names, SE, LAG)
if TREAT not in fit["terms"]:
raise ValueError(f"{TREAT} cannot be separated from the fixed effects in this model (it may move only with time).")
if fit["dropped"]:
warnings.append("Removed by the model (constant within units or collinear): " + ", ".join(fit["dropped"]) + ".")
coefs = pn.coef_table(fit, conf)
main = next(r for r in coefs if r["term"] == TREAT)
est, se, t_stat, p_value, ci_low, ci_high = main["estimate"], main["se"], main["t"], main["p"], main["low"], main["high"]
# %% Specification tests (on the regressors that change within units)
Xw, names_w = X[:, varying], [names[j] for j in varying]
diag = pn.diagnostics(y, Xw, uid, tid, names_w) if varying else {"n_units": N, "n_periods": T, "balanced": bool(pn.is_balanced(uid, tid))}
rho_matrix = diag.pop("_rho_matrix", None)
strict = pn.strict_exogeneity(y, Xw, uid, tid, 0) if varying and varying[0] == 0 else None
if strict:
diag["strict_exog_estimate"], diag["strict_exog_t"], diag["strict_exog_p"] = strict["estimate"], strict["t"], strict["p"]
# %% The same treatment coefficient under every model
compare_rows = []
for m in pn.MODELS:
try:
f2 = fit if m == MODEL else pn.fit(m, y, X, uid, tid, names, SE, LAG)
except (ValueError, np.linalg.LinAlgError):
continue
if TREAT in f2["terms"]:
r = next(x for x in pn.coef_table(f2, conf) if x["term"] == TREAT)
compare_rows.append({"model": m, "label": pn.MODEL_LABEL[m], "estimate": r["estimate"], "se": r["se"], "low": r["low"], "high": r["high"], "p": r["p"], "chosen": m == MODEL})
# %% Checks: what the tests say about this model and these standard errors
checks = []
def add_check(id_, label, status, detail, downgrade=None, fix=None):
c = {"id": id_, "label": label, "status": status, "detail": detail}
if downgrade:
c["downgrade_to"] = downgrade
if fix:
c["fix"] = fix
checks.append(c)
hp, mp = diag.get("hausman_p"), diag.get("mundlak_p")
# The Mundlak row decides when there is one: it holds near 5%, while Hausman reaches 8–15% in short panels whose regressors vary little between units.
effects_reject = mp < 0.05 if mp is not None else (hp is not None and hp < 0.05)
if hp is not None or mp is not None:
parts = []
if hp is not None:
parts.append(f"Hausman {cs.fmt_p(hp)}")
if mp is not None:
parts.append(f"Mundlak (cluster-robust) {cs.fmt_p(mp)}")
reading = ", ".join(parts)
if not diag.get("hausman_full_rank", True):
reading += "; the Hausman difference matrix is not positive definite, so trust the Mundlak row"
elif hp is not None and mp is not None and hp < 0.05 <= mp:
reading += "; Hausman runs high in short panels, so trust the Mundlak row"
if MODEL == "re" and effects_reject:
add_check("hausman", "Fixed or random effects", "concern", f"{reading}: unit differences are related to the regressors, so random effects are biased. Use fixed effects.", "L1", {"label": "Use fixed effects", "options": {"model": "fe"}})
elif MODEL == "re":
add_check("hausman", "Fixed or random effects", "pass", f"{reading}: no sign that unit differences are related to the regressors; random effects are defensible and more precise.")
elif MODEL in ("pooled", "between") and effects_reject:
add_check("hausman", "Fixed or random effects", "concern", f"{reading}: unit differences are related to the regressors, so this model is biased. Use fixed effects.", "L1", {"label": "Use fixed effects", "options": {"model": "fe"}})
elif effects_reject:
add_check("hausman", "Fixed or random effects", "pass", f"{reading}: unit differences are related to the regressors, which is why fixed effects are needed.")
else:
add_check("hausman", "Fixed or random effects", "info", f"{reading}: random effects would also be consistent here and more precise; fixed effects stay safe.")
fu = diag.get("f_unit_p")
if MODEL == "pooled" and fu is not None and fu < 0.05:
add_check("poolability", "Pooling units", "concern", f"The F test of unit effects {cs.fmt_p(fu)}: units differ, so pooled OLS mixes within and between differences. Use fixed effects.", "L1", {"label": "Use fixed effects", "options": {"model": "fe"}})
pl = diag.get("poolability_p")
if pl is not None and pl < 0.05 and MODEL in ("fe", "twfe", "fd", "re"):
add_check("poolability", "One slope for all units", "info", f"Poolability test {cs.fmt_p(pl)}: slopes differ across units, so the coefficient is an average of them with weights that favor units whose treatment moves most.")
if within_share < 0.05 and absorbing:
add_check("within_variation", "Treatment changes within units", "concern", f"Only {within_share:.1%} of the variation in {TREAT} is within units; the estimate rests on little change and is noisy.")
elif absorbing:
add_check("within_variation", "Treatment changes within units", "pass", f"{within_share:.1%} of the variation in {TREAT} is within units.")
if strict:
if strict["p"] < 0.05:
add_check("strict_exog", "No feedback to later treatment", "concern", f"Next period's {TREAT} predicts today's outcome ({cs.fmt_p(strict['p'])}): outcomes may drive later treatment, which biases fixed effects.", "L1")
else:
add_check("strict_exog", "No feedback to later treatment", "pass", f"Next period's {TREAT} does not predict today's outcome ({cs.fmt_p(strict['p'])}): compatible with strict exogeneity.")
cd_p = diag.get("cd_p")
if cd_p is not None:
robust_cd = fit["se"] in ("driscoll_kraay", "cluster_twoway")
long_enough = T >= 20
if cd_p < 0.05 and not robust_cd:
fix = {"label": "Use Driscoll–Kraay standard errors", "options": {"se": "driscoll_kraay"}} if long_enough else {"label": "Cluster by unit and period", "options": {"se": "cluster_twoway"}}
add_check("cross_section", "Errors across units", "concern", f"Pesaran CD {cs.fmt_p(cd_p)}, mean |ρ| {diag['rho_abs_mean']:.2f}: errors move together across units, so these standard errors are too small. {fix['label']}.", None, fix)
elif cd_p < 0.05:
add_check("cross_section", "Errors across units", "pass", f"Pesaran CD {cs.fmt_p(cd_p)}, mean |ρ| {diag['rho_abs_mean']:.2f}: errors move together across units; the chosen standard errors allow for it.")
else:
add_check("cross_section", "Errors across units", "pass", f"Pesaran CD {cs.fmt_p(cd_p)}: no sign that errors move together across units.")
wp = diag.get("wooldridge_p")
if wp is not None:
if wp < 0.05 and fit["se"] == "classical":
add_check("serial_correlation", "Errors over time", "concern", f"Wooldridge test {cs.fmt_p(wp)}: errors are correlated over time, so classical standard errors are too small. Cluster by unit.", None, {"label": "Cluster by unit", "options": {"se": "cluster_unit"}})
elif wp < 0.05:
add_check("serial_correlation", "Errors over time", "pass", f"Wooldridge test {cs.fmt_p(wp)}: errors are correlated over time; the chosen standard errors allow for it.")
else:
add_check("serial_correlation", "Errors over time", "pass", f"Wooldridge test {cs.fmt_p(wp)}: no sign of serial correlation in the errors.")
if fit["se"] in ("cluster_unit", "cluster_twoway") and N < 30:
add_check("clusters", "Enough clusters", "concern", f"Only {N} units: clustered standard errors are unreliable below about 30 clusters. Consider a wild cluster bootstrap outside the app, and read the interval cautiously.")
if fit["se"] == "driscoll_kraay" and T < 50:
add_check("clusters", "Enough periods", "concern", f"Only {T} periods: Driscoll–Kraay tests reject too often on short panels, about 12% at 10 periods, 9% at 20 and 8% at 40 at the 5% level in simulations with no effect. Aim for 50 or more.")
if diag.get("re_negative_variance") and MODEL == "re":
add_check("re_variance", "Random effects variance", "info", "The estimated unit variance came out negative, so it was set to 0 and random effects equal pooled OLS.")
# %% Result
level_note = f" being {treated_level}" if treated_level is not None else ""
MODEL_LABEL = pn.MODEL_LABEL[MODEL]
n = len(y)
claim = {"fe": "L2", "twfe": "L2", "fd": "L2", "re": "L2", "pooled": "L1", "between": "L1"}[MODEL]
keys = ["sigma_e", "sigma_u", "rho_icc", "theta_mean", "re_negative_variance", "hausman_stat", "hausman_df", "hausman_p", "hausman_full_rank", "mundlak_f", "mundlak_df1", "mundlak_df2", "mundlak_p",
"bp_lm_stat", "bp_lm_p", "honda_z", "honda_p", "bp_time_stat", "bp_time_p", "bp_twoway_stat", "bp_twoway_p", "honda_twoway_z", "honda_twoway_p", "king_wu_z", "king_wu_p",
"f_unit_stat", "f_unit_df1", "f_unit_df2", "f_unit_p", "f_time_stat", "f_time_df1", "f_time_df2", "f_time_p", "poolability_stat", "poolability_df1", "poolability_df2", "poolability_p",
"cd_stat", "cd_p", "cd_lm_stat", "cd_lm_df", "cd_lm_p", "cd_sclm_stat", "cd_sclm_p", "cd_pairs", "rho_mean", "rho_abs_mean",
"wooldridge_stat", "wooldridge_df1", "wooldridge_df2", "wooldridge_p", "wooldridge_rho", "wooldridge_fd_stat", "wooldridge_fd_df2", "wooldridge_fd_p", "wooldridge_fd_rho",
"strict_exog_estimate", "strict_exog_t", "strict_exog_p"]
values = {
"estimate": est, "se": se, "t": t_stat, "p_value": p_value, "ci_low": ci_low, "ci_high": ci_high, "df_t": fit["df_t"], "n": n, "n_units": N, "n_periods": T,
"balanced": bool(diag["balanced"]), "model": MODEL, "model_label": MODEL_LABEL.lower(), "se_type": fit["se"], "lag": fit["lag"], "r2": fit["r2"], "within_share": within_share,
**{k: diag.get(k) for k in keys},
"estimand": "Average within-unit effect" if absorbing else ("Average effect, assuming unit differences are unrelated to treatment" if MODEL == "re" else "Association across units"),
"effect_label": f"Change in {Y} per unit of {TREAT}{level_note}",
"claim_level_max": claim,
}
for c in checks:
values[f"check[{c['id']}]"] = c["status"]
diag_rows = []
def add_row(key, test, stat, dof, p, looks_for):
if stat is not None:
diag_rows.append({"key": key, "test": test, "statistic": stat, "df": dof, "p": p, "looks_for": looks_for})
def dof2(a, b):
return f"{int(diag[a])}, {int(diag[b])}" if diag.get(a) is not None else ""
add_row("hausman", "Hausman", diag.get("hausman_stat"), str(int(diag["hausman_df"])) if diag.get("hausman_df") is not None else "", hp, "Random effects are biased: unit differences relate to the regressors")
add_row("mundlak", "Mundlak (cluster-robust)", diag.get("mundlak_f"), dof2("mundlak_df1", "mundlak_df2"), mp, "The same question as Hausman, robust to clustering")
add_row("bp_lm", "Breusch–Pagan LM, unit effects", diag.get("bp_lm_stat"), "1", diag.get("bp_lm_p"), "Unit effects exist (random effects rather than pooled)")
add_row("honda", "Honda, unit effects", diag.get("honda_z"), "", diag.get("honda_p"), "The same, one-sided: a variance can't be negative")
add_row("king_wu", "King–Wu, unit and period effects", diag.get("king_wu_z"), "", diag.get("king_wu_p"), "Unit or period effects, one-sided")
add_row("f_unit", "F test, unit effects", diag.get("f_unit_stat"), dof2("f_unit_df1", "f_unit_df2"), fu, "Fixed effects fit better than pooled OLS")
add_row("f_time", "F test, period effects", diag.get("f_time_stat"), dof2("f_time_df1", "f_time_df2"), diag.get("f_time_p"), "Two-way fixed effects fit better than one-way")
add_row("poolability", "Poolability of slopes", diag.get("poolability_stat"), dof2("poolability_df1", "poolability_df2"), pl, "Slopes differ across units")
add_row("cd", "Pesaran CD", diag.get("cd_stat"), "", cd_p, "Errors move together across units")
add_row("cd_lm", "Breusch–Pagan LM, cross-section", diag.get("cd_lm_stat"), str(int(diag["cd_lm_df"])) if diag.get("cd_lm_df") is not None else "", diag.get("cd_lm_p"), "The same, for few units and many periods")
add_row("wooldridge", "Wooldridge, fixed effects", diag.get("wooldridge_stat"), dof2("wooldridge_df1", "wooldridge_df2"), wp, "Errors are correlated over time")
add_row("wooldridge_fd", "Wooldridge, first differences", diag.get("wooldridge_fd_stat"), f"1, {int(diag['wooldridge_fd_df2'])}" if diag.get("wooldridge_fd_df2") is not None else "", diag.get("wooldridge_fd_p"), "The same, on differenced errors")
add_row("strict_exog", "Lead of the treatment", diag.get("strict_exog_t"), "", diag.get("strict_exog_p"), "Outcomes feed into later treatment")
charts = [cs.chart("compare", "forest", f"Coefficient of {TREAT} under each model", {
"label": cs.col("model", [r["label"] for r in compare_rows], kind="categorical"),
"estimate": cs.col("estimate", [r["estimate"] for r in compare_rows]),
"low": cs.col("low", [r["low"] for r in compare_rows]),
"high": cs.col("high", [r["high"] for r in compare_rows]),
"group": cs.col("model", ["This analysis" if r["chosen"] else "Other models" for r in compare_rows], kind="categorical", levels=["This analysis", "Other models"]),
})]
# Within vs between: the slope of the outcome on the treatment alone, three ways.
x0 = X[:, 0]
single = {m: pn.fit(m, y, x0[:, None], uid, tid, [TREAT], "classical") for m in ("pooled", "between") }
if 0 in varying:
single["fe"] = pn.fit("fe", y, x0[:, None], uid, tid, [TREAT], "classical")
stride = max(1, int(np.ceil(n / 2000)))
means_x, means_y = pn.group_mean(x0, uid, N), pn.group_mean(y, uid, N)
x_points = list(x0[::stride]) + list(means_x)
y_points = list(y[::stride]) + list(means_y)
kinds_points = ["observation"] * len(x0[::stride]) + ["unit mean"] * N
slope = lambda m: float(single[m]["b"][single[m]["terms"].index(TREAT)]) if m in single else None
charts.append(cs.chart("within_between", "within-between", f"{Y} and {TREAT}: within and between units", {
"x": cs.col(TREAT, x_points),
"y": cs.col(Y, y_points),
"kind": cs.col("kind", kinds_points, kind="categorical", levels=["observation", "unit mean"]),
}, controls={"withinSlope": slope("fe"), "betweenSlope": slope("between"), "pooledSlope": slope("pooled"), "xMean": float(x0.mean()), "yMean": float(y.mean())}))
if MODEL in ("fe", "twfe"):
fe_fit = pn.fit("fe", y, X, uid, tid, names, "classical")
ue = pn.unit_effects(fe_fit, y, X, uid, names)
keep_units = np.argsort(-np.abs(ue["effect"] - ue["mean"]), kind="mergesort")[:40]
keep_units = np.sort(keep_units)
z = float(pn.stats.norm.ppf(0.5 + conf / 2))
charts.append(cs.chart("unit_effects", "unit-effects", "Unit fixed effects", {
"label": cs.col(UNIT, [unit_labels[i] for i in keep_units], kind="categorical"),
"effect": cs.col("effect", ue["effect"][keep_units]),
"low": cs.col("low", ue["effect"][keep_units] - z * ue["se"][keep_units]),
"high": cs.col("high", ue["effect"][keep_units] + z * ue["se"][keep_units]),
}, controls={"reference": ue["mean"]}, note=f"The 40 units furthest from the mean, of {N}." if N > 40 else None))
if rho_matrix is not None and N <= 30:
rows_h = [unit_labels[i] for i in range(N) for j in range(N)]
cols_h = [unit_labels[j] for i in range(N) for j in range(N)]
vals_h = [None if not np.isfinite(rho_matrix[i, j]) else float(rho_matrix[i, j]) for i in range(N) for j in range(N)]
charts.append(cs.chart("residual_correlation", "matrix-heatmap", "Residual correlations between units", {
"row": cs.col(UNIT, rows_h, kind="categorical", levels=unit_labels),
"col": cs.col(UNIT, cols_h, kind="categorical", levels=unit_labels),
"value": cs.col("correlation", vals_h, kind="numeric"),
}))
se_label = pn.SE_LABEL[fit["se"]]
summary = (
f"With {MODEL_LABEL.lower()} and {se_label} standard errors, a one-unit change in {TREAT}{level_note} goes with a change of {est:.3f} in {Y} "
f"({conf:.0%} CI [{ci_low:.3f}, {ci_high:.3f}], {cs.fmt_p(p_value)}), across {N} units and {T} periods."
)
concerns = [c for c in checks if c["status"] == "concern"]
if concerns:
summary += " " + concerns[0]["detail"]
notes = [f"Standard errors {se_label}" + (f" (lag {fit['lag']})" if fit["lag"] is not None else "") + f"; t statistics use {int(fit['df_t'])} degrees of freedom."]
if not diag["balanced"]:
notes.append(f"The panel is unbalanced: {n} rows of a possible {N * T}.")
if MODEL == "between" and SE != "classical":
notes.append("The between model has one row per unit, so its standard errors are classical.")
cs.publish({
"method": "causal.panel",
"methodVersion": "1.0.4",
"title": "Panel data model",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"b = {cs.fmt_num(est, 3)}, SE = {cs.fmt_num(se, 3)}, t({int(fit['df_t'])}) = {t_stat:.2f}, {cs.fmt_p(p_value)}, {conf:.0%} CI [{ci_low:.3f}, {ci_high:.3f}]",
"statistics": [
{"key": "estimate", "label": f"Coefficient of {TREAT}", "value": est},
{"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
{"key": "p_value", "label": "p", "value": p_value, "format": "p"},
{"key": "n_units", "label": "Units", "value": N, "format": "int"},
{"key": "n_periods", "label": "Periods", "value": T, "format": "int"},
{"key": "rho_icc", "label": "Share of variance between units", "value": diag.get("rho_icc")},
],
"tables": [
{"key": "coefficients", "title": f"{MODEL_LABEL}, {se_label} standard errors",
"columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"},
{"key": "p", "label": "p", "type": "p"}, {"key": "low", "label": "Low", "type": "number"}, {"key": "high", "label": "High", "type": "number"}],
"rows": coefs},
{"key": "compare", "title": f"The coefficient of {TREAT} under each model",
"columns": [{"key": "label", "label": "Model", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "low", "label": "Low", "type": "number"},
{"key": "high", "label": "High", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
"rows": [{k: r[k] for k in ("label", "estimate", "se", "low", "high", "p")} for r in compare_rows]},
{"key": "diagnostics", "title": "Specification tests",
"columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
{"key": "df", "label": "df", "type": "string"}, {"key": "p", "label": "p", "type": "p"},
{"key": "looks_for", "label": "A small p suggests", "type": "string"}],
"rows": [{k: r[k] for k in ("test", "statistic", "df", "p", "looks_for")} for r in diag_rows]},
],
"assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn", "fail": "fail"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
"checks": checks,
"warnings": warnings,
"notes": notes,
"values": values,
"charts": charts,
})
The estimate is 0.110 (p < .001), with an interval from 0.0758 to 0.144. Only 6.7% of the variation in value is within firms.
That share matters. Fixed effects use nothing else, so a small share means a noisier estimate resting on fewer real changes. The within-between chart shows the split, and the unit-effects chart shows the differences that were removed.
What fixed effects can't see
PredictPredict first
A column called stable never changes within a region. Within that region it's a constant. What happens if you use it as the treatment with fixed effects?
Reveal
Subtracting a region's own average leaves zero: its within share is 0.0%. Only random effects can give a number here (2.85), and the Hausman test below rejects that model at p < .001, so the number leans on an assumption the data speak against.
Fixed or random effects?
ReadRandom effectsRandom effectsA panel model that treats unit differences as noise unrelated to the regressors, which gives more precise estimates when that holds. assume unit differences are unrelated to the regressors. If that holds, the estimate is more precise. If it fails, it's biased.
The Hausman testHausman testCompares fixed and random effects estimates; a large gap suggests unit differences track the regressors, so random effects are biased. compares the two sets of estimates. On Grunfeld it gives p = .312, so random effects are compatible with the data. The related Mundlak testMundlak testAdds each regressor's unit mean to a pooled regression and tests them; nonzero means unit differences are related to the regressors., with clustered errors, gives p = .233: weaker comfort.
A large p-value doesn't show that random effects are right. Fixed effects stay safe either way, at some cost in precision.
Choose the model
CheckpointCheck yourself
A Hausman test gives p = 0.31. Which reading fits?
Show the answer
Answer: b
A non-significant test can reflect low power. Random effects are more precise if their assumption holds, and fixed effects don't need it.
Check yourself · choose all that apply
Which of these do unit fixed effects remove? Select all that apply.
Show the answer
Answer: a, b
Fixed effects remove what stays constant within a unit. Anything that changes over time and moves both treatment and outcome still biases the estimate.
Which errors do you have?
In the appEvery run tests the error structure, and the Assumptions step offers a fix when a check raises a concern.
| Question | Test | On Grunfeld | If flagged |
|---|---|---|---|
| Do unit effects exist? | Breusch–Pagan LMBreusch–Pagan LM test for panel effectsAsks whether pooled OLS residuals of one unit move together, which would mean unit effects exist. Honda and King–Wu are its one-sided forms. | p < .001 | Don't pool |
| Do errors move together across units? | Pesaran CDPesaran CD testAverages the correlations between units' residuals; a small p-value means errors move together across units, as with a common shock. | p < .001 | Driscoll–KraayDriscoll–Kraay standard errorsStandard errors that allow errors to be correlated across units and over time, built from each period's sum across units. or two-way clustering |
| The same, with squared correlations | Breusch–Pagan LM for cross-sectional dependenceBreusch–Pagan LM test for cross-sectional dependenceSums the squared correlations between every pair of units' residuals, so signs can't cancel; a small p-value means errors move together. | p < .001 | As above |
| Are errors correlated over time? | WooldridgeWooldridge test for serial correlationTests whether a unit's errors are correlated over time; if so, classical standard errors are too small, so cluster by unit. | p < .001 | Cluster by unit |
Two different tests share the Breusch–Pagan LM name. The first row's tests whether unit effects exist; the cross-sectional one squares every pair of units' residual correlations, so opposite signs can't cancel.
Here, the studio also warns that 10 firms are too few for clustering to be reliable.
Match the fix
CheckpointCheck yourself
The Breusch–Pagan LM test gives p < .001. What does it support?
Show the answer
Answer: b
It asks whether unit effects exist at all. Choosing between fixed and random effects is a separate question, for the Hausman test.
Check yourself
A panel of 48 states over 17 years has a Pesaran CD test with p < .001. A national recession hit everyone. What should change?
Show the answer
Answer: b
Unit effects don't remove shocks shared within a period. Two-way effects remove the average shock, and errors can still be correlated across units, so the standard errors must allow for that.
Check yourself
The Wooldridge test rejects, and you're using classical standard errors. What does that tell you?
Show the answer
Answer: b
Serial correlation mainly distorts the standard errors. Clustering by unit allows any correlation over time within a unit.
What remains an assumption
ReflectFixed effects can't deal with feedback. If today's outcome moves tomorrow's treatment, strict exogeneity fails. The method tests a lead of the treatment: on Grunfeld, p = .938, which is compatible with no feedback.
Nor can they handle a confounder that changes over time. So the app caps these designs at L2, and pooled models at L1.
Think of your own panel. What changes over time, inside a unit, and could move both treatment and outcome?
Try it
In the appIn the Causal studio, start from Treatment that changes over time (panel fixed effects).
import pandas as pd
from linearmodels.panel import PanelOLS, RandomEffects, compare
df = pd.read_csv("grunfeld.csv").set_index(["firm", "year"])
fe = PanelOLS.from_formula("inv ~ value + capital + EntityEffects", df).fit(
cov_type="clustered", cluster_entity=True
)
re = RandomEffects.from_formula("inv ~ 1 + value + capital", df).fit()
print(compare({"FE": fe, "RE": re}))library(plm)
library(lmtest)
library(sandwich)
df <- read.csv("grunfeld.csv")
fe <- plm(inv ~ value + capital, df, index = c("firm", "year"), model = "within")
re <- plm(inv ~ value + capital, df, index = c("firm", "year"), model = "random")
coeftest(fe, vcov = vcovHC(fe, cluster = "group"))
phtest(fe, re) # Hausman
pcdtest(fe) # Pesaran CDRecap
Recap- Fixed effects compare a unit with itself, removing everything constant within it.
- A treatment that never changes within a unit can't be estimated that way.
- Hausman compares fixed and random effects, and a large p-value isn't proof of random effects.
- Let Pesaran CD and Wooldridge guide the standard errors. Time-varying confounding stays an assumption.
Concepts in this lesson