CCausal inference · causal.panel
Panel data models (fixed effects, random effects, first differences)
When the same units are measured repeatedly, how does the outcome change when a unit's own treatment changes?
Linear models for panel data: one-way and two-way fixed effects, random effects (Swamy–Arora), first differences, pooled OLS and between. Standard errors can be clustered by unit or two-way, or follow Driscoll–Kraay or Newey–West. Every run tests the specification: Hausman and Mundlak (fixed or random effects), Breusch–Pagan and Honda (are there effects at all), F tests and poolability, Pesaran CD (cross-sectional dependence), Wooldridge (serial correlation) and a lead of the treatment (strict exogeneity).
A real result
Example “Fe grunfeld”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
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.
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.
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
- Fe grunfeldpanel_grunfeld · covariates: capital · outcome: inv · time: year · treatment: value · unit: firm
- Twfe produc driscoll kraaypanel_produc · covariates: log_pc, log_emp, unemp · outcome: log_gsp · time: year · treatment: log_pcap · unit: state
- Re grunfeldpanel_grunfeld · covariates: capital · outcome: inv · time: year · treatment: value · unit: firm
- Fd grunfeld newey westpanel_grunfeld · covariates: capital · outcome: inv · time: year · treatment: value · unit: firm
- Twfe empluk unbalanced twowaypanel_empluk · covariates: log_capital, log_output · outcome: log_emp · time: year · treatment: log_wage · unit: firm
- Re empluk unbalancedpanel_empluk · covariates: log_capital, log_output · outcome: log_emp · time: year · treatment: log_wage · unit: firm
- Pooled producpanel_produc · covariates: log_pc · outcome: log_gsp · time: year · treatment: log_pcap · unit: state
- Between producpanel_produc · covariates: log_emp · outcome: log_gsp · time: year · treatment: log_pcap · unit: state
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Causal inference (experiments, DiD, IV, RDD) · DS & ML Decision Guide · Explain — why is it happening?
What you need
- Outcomenumeric · 1 column
- The numeric outcome, one value per unit and period.
- Treatmentnumeric / boolean / categorical · 1 column
- The regressor whose coefficient is the headline: a dose, a price, or a two-level on/off. Fixed effects need it to change within units.
- Unitcategorical / numeric · 1 column
- Who is measured repeatedly (person, firm, region). One row per unit and period.
- Timenumeric / temporal · 1 column
- The period of each row (year, month, date). Sorted; periods nobody was observed in don't count.
- Covariatesnumeric / boolean · 0–30 columns
- Other regressors. Avoid variables the treatment itself could change. Fixed effects drop those constant within units.
Choices you make
statistics
- Modeldefault fe
How the unit differences are handled. Fixed effects are the safe default when units differ in ways you can't measure.
- Fixed effects (within)(default) — Removes everything constant within a unit, measured or not.
- Two-way fixed effects — Also removes shocks common to all units in a period.
- First differences — Period-to-period changes. Preferable when the errors are close to a random walk.
- Random effects (Swamy–Arora) — More precise, but biased if the Hausman test rejects. Keeps regressors constant within units.
- Pooled OLS — Ignores the panel: treats every row as independent evidence.
- Between (unit means) — One row per unit, on its means: uses only differences between units.
- Standard errorsdefault cluster_unit
How errors are allowed to depend. Clustering by unit allows any correlation over time within a unit.
- Clustered by unit(default) — Any correlation over time within a unit. Needs about 30 or more units.
- Clustered by unit and period — Also allows correlation across units within a period.
- Driscoll–Kraay — For errors correlated across units and over time. Needs a long panel (about 20 or more periods).
- Newey–West within unit — Correlation within a unit that fades with the time apart; no correlation across units.
- Classical — Independent, equal-variance errors; rarely credible in a panel.
- Lags for Driscoll–Kraay and Newey–Westdefault —
How many periods of autocorrelation the standard errors allow. Automatic: floor(4 (T / 100)^(2/9)).
hypothesis
- Treated leveldefault —
With a two-level treatment, the level coded 1 (default "true" or the last level).
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
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.
Strict exogeneity
A unit's errors in any period are unrelated to its treatment in every period: no feedback from outcomes to later treatment. A lead of the treatment tests it.
No time-varying confoundingNot checked from data: state why it holds
Fixed effects remove what stays constant within a unit. Anything that changes over time and moves both treatment and outcome still biases the estimate.
Treatment varies within units
Fixed effects use only changes within a unit; little change means a noisy estimate that rests on few units.
Errors over time
A Wooldridge test shows whether a unit's errors are correlated over time, which calls for clustered standard errors.
Errors across units
A Pesaran CD test shows whether errors are correlated across units in the same period (Driscoll–Kraay errors allow for it).
Enough clusters
Clustered standard errors need roughly 30 or more clusters (or periods for Driscoll–Kraay).
Fixed or random effects
A Hausman test of whether random effects are consistent; when it rejects, use fixed effects.
One slope for all units
Whether one coefficient fits every unit or the units differ.
Random effects variance
Whether the unit effects vary at all; with none, pooled OLS is enough.
What it reports
- Tests: Coefficient of the treatment
- estimate
- How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
- se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- t
- An estimate divided by its standard error, compared with a t distribution.
- p_value
- How surprising your data would be if the null hypothesis were true, as a probability.
- ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- df_t
- A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
- n
- How many independent units the analysis used; it sets precision and power.
- n_units
- How many independent units the analysis used; it sets precision and power.
- n_periods
- How many independent units the analysis used; it sets precision and power.
- balanced
- True when every unit is observed in every period, so the panel has no gaps; false when some unit–period rows are missing.
- model
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- model_label
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- se_type
- Standard errors that stay valid when residual variance is not constant; HC3 suits small samples.
- lag
- Periods of autocorrelation allowed by Driscoll–Kraay or Newey–West standard errors. Empty when another standard error type is used.
- r2
- The share of the outcome's variance explained by the model, from 0 to 1.
- within_share
- A panel model that compares each unit with itself, removing everything constant within a unit, measured or not.
- sigma_e
- A panel model that treats unit differences as noise unrelated to the regressors, which gives more precise estimates when that holds.
- sigma_u
- A panel model that treats unit differences as noise unrelated to the regressors, which gives more precise estimates when that holds.
- rho_icc
- The share of variance due to differences between groups (or raters' agreement on the same subjects).
- theta_mean
- A panel model that treats unit differences as noise unrelated to the regressors, which gives more precise estimates when that holds.
- re_negative_variance
- A panel model that treats unit differences as noise unrelated to the regressors, which gives more precise estimates when that holds.
- hausman_stat
- Compares fixed and random effects estimates; a large gap suggests unit differences track the regressors, so random effects are biased.
- hausman_df
- How much independent information is left to estimate variability after fitting the model.
- hausman_p
- Compares fixed and random effects estimates; a large gap suggests unit differences track the regressors, so random effects are biased.
- hausman_full_rank
- Compares fixed and random effects estimates; a large gap suggests unit differences track the regressors, so random effects are biased.
- mundlak_f
- The ratio of explained to unexplained variance, used by ANOVA and regression tests.
- mundlak_df1
- How much independent information is left to estimate variability after fitting the model.
- mundlak_df2
- How much independent information is left to estimate variability after fitting the model.
- mundlak_p
- Adds each regressor's unit mean to a pooled regression and tests them; nonzero means unit differences are related to the regressors.
- bp_lm_stat
- Asks whether pooled OLS residuals of one unit move together, which would mean unit effects exist. Honda and King–Wu are its one-sided forms.
- bp_lm_p
- Asks whether pooled OLS residuals of one unit move together, which would mean unit effects exist. Honda and King–Wu are its one-sided forms.
- honda_z
- An estimate in standard-error units, compared with the standard normal distribution.
- honda_p
- Asks whether pooled OLS residuals of one unit move together, which would mean unit effects exist. Honda and King–Wu are its one-sided forms.
- bp_time_stat
- Asks whether pooled OLS residuals of one unit move together, which would mean unit effects exist. Honda and King–Wu are its one-sided forms.
- bp_time_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- bp_twoway_stat
- Asks whether pooled OLS residuals of one unit move together, which would mean unit effects exist. Honda and King–Wu are its one-sided forms.
- bp_twoway_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- honda_twoway_z
- An estimate in standard-error units, compared with the standard normal distribution.
- honda_twoway_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- king_wu_z
- An estimate in standard-error units, compared with the standard normal distribution.
- king_wu_p
- Asks whether pooled OLS residuals of one unit move together, which would mean unit effects exist. Honda and King–Wu are its one-sided forms.
- f_unit_stat
- A panel model that compares each unit with itself, removing everything constant within a unit, measured or not.
- f_unit_df1
- How much independent information is left to estimate variability after fitting the model.
- f_unit_df2
- How much independent information is left to estimate variability after fitting the model.
- f_unit_p
- Whether all units can share one model. F tests ask whether unit levels differ and whether slopes differ across units.
- f_time_stat
- A panel model that compares each unit with itself, removing everything constant within a unit, measured or not.
- f_time_df1
- How much independent information is left to estimate variability after fitting the model.
- f_time_df2
- How much independent information is left to estimate variability after fitting the model.
- f_time_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- poolability_stat
- Whether all units can share one model. F tests ask whether unit levels differ and whether slopes differ across units.
- poolability_df1
- How much independent information is left to estimate variability after fitting the model.
- poolability_df2
- How much independent information is left to estimate variability after fitting the model.
- poolability_p
- Whether all units can share one model. F tests ask whether unit levels differ and whether slopes differ across units.
- cd_stat
- Averages the correlations between units' residuals; a small p-value means errors move together across units, as with a common shock.
- cd_p
- Averages the correlations between units' residuals; a small p-value means errors move together across units, as with a common shock.
- cd_lm_stat
- Sums the squared correlations between every pair of units' residuals, so signs can't cancel; a small p-value means errors move together.
- cd_lm_df
- Sums the squared correlations between every pair of units' residuals, so signs can't cancel; a small p-value means errors move together.
- cd_lm_p
- Sums the squared correlations between every pair of units' residuals, so signs can't cancel; a small p-value means errors move together.
- cd_sclm_stat
- Averages the correlations between units' residuals; a small p-value means errors move together across units, as with a common shock.
- cd_sclm_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- cd_pairs
- Averages the correlations between units' residuals; a small p-value means errors move together across units, as with a common shock.
- rho_mean
- Averages the correlations between units' residuals; a small p-value means errors move together across units, as with a common shock.
- rho_abs_mean
- Averages the correlations between units' residuals; a small p-value means errors move together across units, as with a common shock.
- wooldridge_stat
- Tests whether a unit's errors are correlated over time; if so, classical standard errors are too small, so cluster by unit.
- wooldridge_df1
- How much independent information is left to estimate variability after fitting the model.
- wooldridge_df2
- How much independent information is left to estimate variability after fitting the model.
- wooldridge_p
- Tests whether a unit's errors are correlated over time; if so, classical standard errors are too small, so cluster by unit.
- wooldridge_rho
- Tests whether a unit's errors are correlated over time; if so, classical standard errors are too small, so cluster by unit.
- wooldridge_fd_stat
- Tests whether a unit's errors are correlated over time; if so, classical standard errors are too small, so cluster by unit.
- wooldridge_fd_df2
- How much independent information is left to estimate variability after fitting the model.
- wooldridge_fd_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- wooldridge_fd_rho
- Tests whether a unit's errors are correlated over time; if so, classical standard errors are too small, so cluster by unit.
- strict_exog_estimate
- A unit's errors in any period are unrelated to its treatment in every period, so today's outcome doesn't move tomorrow's treatment.
- strict_exog_t
- An estimate divided by its standard error, compared with a t distribution.
- strict_exog_p
- A unit's errors in any period are unrelated to its treatment in every period, so today's outcome doesn't move tomorrow's treatment.
- estimand
- The exact quantity an analysis targets, such as a difference in means or a ratio of medians.
- effect_label
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- claim_level_max
- How strong a causal statement the design supports, from association up to a causal effect.
Per group, level or term: check[<id>]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses nanoparquet, codesplashr.
Default traps between the two languages
- The Mundlak statistic comes from a leave-one-cluster-out jackknife on nearly collinear unit means, so each machine's linear algebra library moves it by a few parts in 10^10, and its p-value by about ten times that. It has its own tolerance of 1e-8.
- Wooldridge's serial-correlation tests use G/(G − 1) · (n − 1)/(n − k) and F(1, G − 1), as Stata's xtserial does (Drukker 2003). plm::pwartest and pwfdtest use neither: the statistic differs by that factor and the p-value by the reference. Simulated with no serial correlation (2,000 panels each): plm's form 6.9/6.1% at N = 40, T = 10 and 9.3/10.5% at N = 20, T = 5; this form 5.6/4.9% and 7.0/7.4%.
- The Mundlak test uses CV3, the leave-one-cluster-out jackknife (MacKinnon, Nielsen & Webb 2023), not CV1: simulated CV1 5.6–11.6%, CV3 5.0–6.8% (N = 20–200, 500 panels each; a rerun at N = 40 with regressors that have no between-unit part gave 7.9% over 1,000), and a rejection only steers to fixed effects, which stay valid. The Hausman row matches plm::phtest and runs high in short panels whose regressors vary little between units (8–15%), so the Mundlak row decides the fixed-or-random check when there is one.
- Driscoll–Kraay tests reject too often on short panels (simulated, N = 30: 12% at T = 10, 9% at 20, 8% at 40); the card carries a concern below 50 periods.
- Both engines run the same twin (codesplash.causal.panel ↔ cs_panel_*), checked against R plm (tests/crosscheck/w2s4_panel.R).
- Clustered standard errors use G/(G − 1) · (n − 1)/(n − k) with absorbed fixed effects not counted, as plm's 'sss' and fixest for effects nested in clusters; Stata's xtreg also counts the intercept in k, and fixest counts period effects under one-way clustering, so their standard errors differ slightly.
- Two-way clustering uses the smaller cluster count in the factor (fixest's default); linearmodels and Stata's user commands scale each part separately.
- Hausman: when V_FE − V_RE is not positive definite the statistic uses its positive part with df = that rank, so it stays non-negative; plm::phtest inverts the indefinite matrix and can differ or go negative. The Mundlak row is cluster-robust and needs no such fix.
- First differences keep an intercept (a linear trend in levels), as plm does; linearmodels' FirstDifferenceOLS drops it.
- Differencing and the Wooldridge tests use the previous observed row of a unit, as plm does, so gaps in a unit's periods count as one step.
The exact script CodeSplash ran for example “Fe grunfeld” · 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 exact script CodeSplash ran for example “Fe grunfeld” · 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
))
Sources
- Drukker, D. M. (2003). Testing for serial correlation in linear panel-data models. The Stata Journal, 3, 168–177.
- MacKinnon, J. G., Nielsen, M. Ø., & Webb, M. D. (2023). Cluster-robust inference: a guide to empirical practice. Journal of Econometrics, 232, 272–299.
- Baltagi, B. H. (2021). Econometric analysis of panel data (6th ed.). Springer.
- Wooldridge, J. M. (2010). Econometric analysis of cross section and panel data (2nd ed.). MIT Press (ch. 10).
- Hausman, J. A. (1978). Specification tests in econometrics. Econometrica, 46, 1251–1271.
- Mundlak, Y. (1978). On the pooling of time series and cross section data. Econometrica, 46, 69–85.
- Breusch, T. S., & Pagan, A. R. (1980). The Lagrange multiplier test and its applications to model specification in econometrics. Review of Economic Studies, 47, 239–253.
- Honda, Y. (1985). Testing the error components model with non-normal disturbances. Review of Economic Studies, 52, 681–690.
- Pesaran, M. H. (2021). General diagnostic tests for cross-sectional dependence in panels. Empirical Economics, 60, 13–50.
- Driscoll, J. C., & Kraay, A. C. (1998). Consistent covariance matrix estimation with spatially dependent panel data. Review of Economics and Statistics, 80, 549–560.
- Cameron, A. C., Gelbach, J. B., & Miller, D. L. (2011). Robust inference with multiway clustering. Journal of Business & Economic Statistics, 29, 238–249.
- Swamy, P. A. V. B., & Arora, S. S. (1972). The exact finite sample properties of the estimators of coefficients in the error components regression models. Econometrica, 40, 261–275.
- Baltagi, B. H., & Chang, Y.-J. (1994). Incomplete panels: a comparative study of alternative estimators for the unbalanced one-way error component regression model. Journal of Econometrics, 62, 67–89.
From the CodeSplash method registry · causal.panel v1.0.4.