Robust standard errors: HC3, clusters and Newey–West
You can keep the coefficients and fix their uncertainty. Choose among HC3, cluster-robust and Newey–West based on how your data depart from independence and constant variance.
What runs in CodeSplash
- Linear regression (OLS) Verified in Python and R
You will be able to
- Explain the sandwich idea in words
- Choose HC3, cluster-robust or Newey–West from how the data were collected
- Say why a few clusters make cluster-robust errors unreliable
- Recognize what robust errors don't fix
Same line, honest uncertainty
ReadClassical standard errors assume every error has the same variance and no error is related to another. When that fails, the coefficients can still be useful, but the classical formula gives the wrong uncertainty.
Robust standard errorsRobust standard errorsStandard errors that stay valid when residual variance is not constant; HC3 suits small samples. keep the coefficients and replace the variance formula:
The two outer pieces are the bread and is the meat, so this is called a sandwich estimator. What you assume about decides which kind you get.
Match the error to the problem
Read| Your data | Standard errors |
|---|---|
| Independent rows, changing spread | HC3 |
| Rows grouped into clusters | Cluster-robust |
| Rows in time order | Newey–West (HAC) |
| Clean data | Classical is fine |
Pick from how the data were collected, not from which one gives the smallest -value. Choosing after seeing results is a form of p-hacking.
HC3
ReadEach HC variant uses squared residuals in the meat. HC0 is White's original. HC3 divides each by , where is the row's leverage, which matters because high-leverage rows have artificially small residuals.
HC3 holds up best in small samples, so it's the one CodeSplash recommends. The airquality interaction from the earlier lesson uses HC3 errors, since its residuals fan out as ozone rises.
Clusters
ExploreWhen rows come in groups (students in schools, repeat visits by customers), errors within a group are related. Each extra row in the same group adds less information than it seems to.
BExplorable · When observations come in clusters
What happens to a t test when students come in classrooms and you ignore it?
There is no true effect. How often does the naive t test reject?
Commit your prediction above to see the result
Make your prediction to see the result.
Raise the within-cluster correlation and watch the rejection rate of a naive test. Cluster-robustCluster-robust standard errorsStandard errors that allow any correlation within a cluster and assume independence between clusters. errors allow any correlation within a cluster and assume independence between clusters.
How many clusters?
PredictPredict first
A model has 190 rows grouped into 4 clusters. How much should you trust its cluster-robust standard errors?
Reveal
Unreliable. The asymptotics run on the number of clusters, not rows. With roughly fewer than 30 to 40 clusters they tend to be too small. Note how this model's test has only 3 denominator degrees of freedom.
Time order
In the appRows in time can carry part of each error into the next. Newey–WestNewey–West standard errorsStandard errors that allow correlation between nearby observations in a series, up to a chosen lag. errors allow that up to a chosen lag, weighting closer lags more:
R² = .81, adjusted R² = .80, F(2, 117) = 100.41, p < .001
- R²
- 0.8071
- Adjusted R²
- 0.8038
- F
- 100.41
- p (F test)
- < .001
- Residual SE
- 1.226
- AIC
- 394.39
Effect size
- Cohen's f² 4.183
- R² 0.8071
Plots
View data
| Cook's distance | Fitted | Leverage | Residual | Standardized residual |
|---|---|---|---|---|
| 4.260e-5 | 3.775 | 0.0264 | −0.0831 | −0.0687 |
| 0.0019 | 7.539 | 0.0107 | 0.8768 | 0.7191 |
| 0.0131 | 9.180 | 0.0200 | 1.680 | 1.384 |
| 0.0005 | 6.045 | 0.0111 | 0.4415 | 0.3621 |
| 0.0063 | 10.829 | 0.0496 | −0.7207 | −0.6030 |
| 0.0002 | 5.192 | 0.0199 | 0.2110 | 0.1739 |
| 0.0006 | 6.408 | 0.0155 | −0.4090 | −0.3363 |
| 0.0005 | 11.156 | 0.0487 | −0.2097 | −0.1754 |
| 0.0078 | 9.985 | 0.0201 | −1.301 | −1.072 |
| 0.0093 | 4.965 | 0.0279 | −1.192 | −0.9862 |
| 0.0028 | 9.032 | 0.0264 | −0.6712 | −0.5549 |
| 0.0039 | 7.453 | 0.0126 | −1.164 | −0.9552 |
| 2.072e-5 | 8.153 | 0.0135 | −0.0820 | −0.0674 |
| 3.451e-5 | 5.491 | 0.0120 | 0.1124 | 0.0922 |
| 0.0007 | 3.455 | 0.0272 | −0.3310 | −0.2737 |
| 0.0010 | 3.387 | 0.0425 | 0.3102 | 0.2586 |
| 0.0542 | 10.317 | 0.0277 | −2.887 | −2.389 |
| 0.0010 | 8.379 | 0.0365 | −0.3449 | −0.2866 |
| 0.0087 | 9.912 | 0.0200 | 1.374 | 1.132 |
| 0.0078 | 9.603 | 0.0166 | −1.434 | −1.180 |
| 0.0109 | 8.442 | 0.0405 | 1.058 | 0.8812 |
| 0.0020 | 2.375 | 0.0440 | −0.4296 | −0.3584 |
| 0.0003 | 6.440 | 0.0120 | −0.3100 | −0.2544 |
| 0.0004 | 6.276 | 0.0247 | 0.2549 | 0.2105 |
| 0.0006 | 10.484 | 0.0317 | 0.2784 | 0.2308 |
| 0.0502 | 8.836 | 0.0168 | 3.611 | 2.970 |
| 0.0108 | 8.906 | 0.0396 | 1.064 | 0.8854 |
| 4.974e-5 | 6.619 | 0.0242 | −0.0940 | −0.0776 |
| 0.0014 | 9.864 | 0.0201 | 0.5416 | 0.4463 |
| 0.0072 | 9.172 | 0.0142 | 1.489 | 1.224 |
| 0.0029 | 2.835 | 0.0445 | 0.5137 | 0.4286 |
| 0.0002 | 5.325 | 0.0217 | −0.2177 | −0.1795 |
| 0.0003 | 8.438 | 0.0129 | −0.2988 | −0.2453 |
| 8.211e-6 | 5.179 | 0.0136 | −0.0515 | −0.0423 |
| 0.0155 | 4.306 | 0.0193 | −1.869 | −1.539 |
| 0.0007 | 4.899 | 0.0168 | −0.4368 | −0.3593 |
| 0.0031 | 8.317 | 0.0249 | 0.7350 | 0.6072 |
| 0.0092 | 9.666 | 0.0170 | −1.535 | −1.263 |
| 2.973e-5 | 4.360 | 0.0189 | −0.0826 | −0.0680 |
| 0.0162 | 9.953 | 0.0198 | 1.885 | 1.553 |
| 0.0195 | 9.491 | 0.0233 | 1.897 | 1.566 |
| 0.0055 | 3.154 | 0.0668 | −0.5663 | −0.4782 |
| 0.0182 | 1.937 | 0.0569 | 1.132 | 0.9506 |
| 0.0054 | 9.831 | 0.0276 | −0.9147 | −0.7567 |
| 0.0011 | 4.782 | 0.0159 | −0.5381 | −0.4424 |
| 0.0004 | 5.941 | 0.0225 | −0.2879 | −0.2375 |
| 0.0026 | 4.038 | 0.0219 | −0.7220 | −0.5955 |
| 0.0013 | 8.868 | 0.0331 | 0.4053 | 0.3363 |
| 0.0005 | 3.272 | 0.0336 | 0.2382 | 0.1976 |
| 0.0010 | 6.754 | 0.0105 | 0.6583 | 0.5398 |
| 0.0011 | 4.929 | 0.0304 | −0.3963 | −0.3283 |
| 3.629e-8 | 10.079 | 0.0220 | −0.0027 | −0.0022 |
| 0.0005 | 9.018 | 0.0624 | 0.1818 | 0.1531 |
| 0.0328 | 6.013 | 0.0682 | −1.372 | −1.159 |
| 0.0051 | 5.255 | 0.0132 | −1.301 | −1.069 |
| 0.0010 | 9.123 | 0.0158 | 0.5344 | 0.4394 |
| 0.0201 | 2.348 | 0.0489 | 1.295 | 1.083 |
| 0.0006 | 6.514 | 0.0091 | 0.5592 | 0.4582 |
| 0.0021 | 9.819 | 0.0187 | −0.7060 | −0.5813 |
| 0.0963 | 9.432 | 0.0345 | −3.424 | −2.843 |
First 60 of 120 rows.
View data
| Row | Term | Predictor given the others | y given the others |
|---|---|---|---|
| row 1 | x1 | −2.727 | −2.895 |
| row 2 | x1 | 0.6590 | 1.556 |
| row 3 | x1 | 1.356 | 3.079 |
| row 4 | x1 | −0.7826 | −0.3656 |
| row 5 | x1 | 2.384 | 1.738 |
| row 6 | x1 | −2.280 | −2.141 |
| row 7 | x1 | −1.179 | −1.625 |
| row 8 | x1 | 2.780 | 2.657 |
| row 9 | x1 | 2.758 | 1.544 |
| row 10 | x1 | −2.709 | −3.986 |
| row 11 | x1 | 2.456 | 1.861 |
| row 12 | x1 | −0.1284 | −1.296 |
| row 13 | x1 | 1.314 | 1.273 |
| row 14 | x1 | −1.498 | −1.433 |
| row 15 | x1 | −3.212 | −3.644 |
| row 16 | x1 | −2.624 | −2.396 |
| row 17 | x1 | 2.405 | −0.4074 |
| row 18 | x1 | 2.159 | 1.882 |
| row 19 | x1 | 2.298 | 3.744 |
| row 20 | x1 | 2.218 | 0.8530 |
| row 21 | x1 | 2.289 | 3.419 |
| row 22 | x1 | −3.883 | −4.434 |
| row 23 | x1 | −0.9848 | −1.326 |
| row 24 | x1 | −1.577 | −1.371 |
| row 25 | x1 | 2.461 | 2.817 |
| row 26 | x1 | 1.110 | 4.755 |
| row 27 | x1 | 2.656 | 3.803 |
| row 28 | x1 | −1.269 | −1.403 |
| row 29 | x1 | 2.735 | 3.362 |
| row 30 | x1 | 1.746 | 3.290 |
| row 31 | x1 | −4.580 | −4.210 |
| row 32 | x1 | −2.252 | −2.540 |
| row 33 | x1 | 0.8701 | 0.5986 |
| row 34 | x1 | −1.755 | −1.862 |
| row 35 | x1 | −2.553 | −4.502 |
| row 36 | x1 | −1.780 | −2.273 |
| row 37 | x1 | 0.2952 | 1.039 |
| row 38 | x1 | 2.290 | 0.8259 |
| row 39 | x1 | −2.463 | −2.623 |
| row 40 | x1 | 2.723 | 4.693 |
| row 41 | x1 | 2.689 | 4.670 |
| row 42 | x1 | −2.392 | −3.033 |
| row 43 | x1 | −5.421 | −4.459 |
| row 44 | x1 | 1.823 | 0.9656 |
| row 45 | x1 | −2.125 | −2.729 |
| row 46 | x1 | −1.796 | −2.141 |
| row 47 | x1 | −2.954 | −3.769 |
| row 48 | x1 | 2.492 | 2.975 |
| row 49 | x1 | −3.961 | −3.847 |
| row 50 | x1 | −0.6323 | 0.0062 |
| row 51 | x1 | −2.802 | −3.286 |
| row 52 | x1 | 2.948 | 3.038 |
| row 53 | x1 | 3.126 | 3.406 |
| row 54 | x1 | −2.566 | −4.019 |
| row 55 | x1 | −1.681 | −3.035 |
| row 56 | x1 | 2.095 | 2.695 |
| row 57 | x1 | −4.973 | −3.834 |
| row 58 | x1 | −0.6722 | −0.1340 |
| row 59 | x1 | 2.592 | 1.968 |
| row 60 | x1 | 2.965 | −0.3667 |
First 60 of 240 rows.
View data
| Row | Component + residual | Term | Predictor |
|---|---|---|---|
| row 1 | 2.662 | x1 | 2.662 |
| row 2 | 7.198 | x1 | 6.130 |
| row 3 | 9.007 | x1 | 7.104 |
| row 4 | 5.274 | x1 | 4.686 |
| row 5 | 7.850 | x1 | 8.310 |
| row 6 | 3.714 | x1 | 3.396 |
| row 7 | 4.255 | x1 | 4.522 |
| row 8 | 8.743 | x1 | 8.681 |
| row 9 | 7.273 | x1 | 8.313 |
| row 10 | 1.936 | x1 | 3.033 |
| row 11 | 7.391 | x1 | 7.818 |
| row 12 | 4.571 | x1 | 5.561 |
| row 13 | 6.896 | x1 | 6.766 |
| row 14 | 4.264 | x1 | 4.026 |
| row 15 | 1.970 | x1 | 2.231 |
| row 16 | 3.008 | x1 | 2.615 |
| row 17 | 5.538 | x1 | 8.170 |
| row 18 | 7.304 | x1 | 7.417 |
| row 19 | 9.598 | x1 | 7.974 |
| row 20 | 6.637 | x1 | 7.826 |
| row 21 | 8.819 | x1 | 7.525 |
| row 22 | 1.059 | x1 | 1.443 |
| row 23 | 4.502 | x1 | 4.665 |
| row 24 | 4.595 | x1 | 4.208 |
| row 25 | 8.796 | x1 | 8.259 |
| row 26 | 10.656 | x1 | 6.831 |
| row 27 | 9.230 | x1 | 7.918 |
| row 28 | 4.571 | x1 | 4.524 |
| row 29 | 9.061 | x1 | 8.261 |
| row 30 | 9.091 | x1 | 7.371 |
| row 31 | 1.649 | x1 | 1.101 |
| row 32 | 3.347 | x1 | 3.456 |
| row 33 | 6.452 | x1 | 6.546 |
| row 34 | 3.820 | x1 | 3.754 |
| row 35 | 1.165 | x1 | 2.941 |
| row 36 | 3.330 | x1 | 3.653 |
| row 37 | 7.040 | x1 | 6.113 |
| row 38 | 6.606 | x1 | 7.894 |
| row 39 | 3.032 | x1 | 3.020 |
| row 40 | 10.424 | x1 | 8.279 |
| row 41 | 10.268 | x1 | 8.117 |
| row 42 | 2.224 | x1 | 2.705 |
| row 43 | 1.390 | x1 | 0.2507 |
| row 44 | 6.947 | x1 | 7.622 |
| row 45 | 2.948 | x1 | 3.380 |
| row 46 | 3.792 | x1 | 3.956 |
| row 47 | 1.943 | x1 | 2.584 |
| row 48 | 8.443 | x1 | 7.793 |
| row 49 | 1.949 | x1 | 1.659 |
| row 50 | 5.818 | x1 | 5.003 |
| row 51 | 2.654 | x1 | 2.958 |
| row 52 | 8.736 | x1 | 8.473 |
| row 53 | 8.717 | x1 | 8.276 |
| row 54 | 2.183 | x1 | 3.447 |
| row 55 | 2.647 | x1 | 3.828 |
| row 56 | 8.369 | x1 | 7.597 |
| row 57 | 2.000 | x1 | 0.6837 |
| row 58 | 5.616 | x1 | 4.903 |
| row 59 | 7.698 | x1 | 8.149 |
| row 60 | 5.124 | x1 | 8.289 |
First 60 of 240 rows.
View data
| Cook's distance | Row |
|---|---|
| 4.260e-5 | 1 |
| 0.0019 | 2 |
| 0.0131 | 3 |
| 0.0005 | 4 |
| 0.0063 | 5 |
| 0.0002 | 6 |
| 0.0006 | 7 |
| 0.0005 | 8 |
| 0.0078 | 9 |
| 0.0093 | 10 |
| 0.0028 | 11 |
| 0.0039 | 12 |
| 2.072e-5 | 13 |
| 3.451e-5 | 14 |
| 0.0007 | 15 |
| 0.0010 | 16 |
| 0.0542 | 17 |
| 0.0010 | 18 |
| 0.0087 | 19 |
| 0.0078 | 20 |
| 0.0109 | 21 |
| 0.0020 | 22 |
| 0.0003 | 23 |
| 0.0004 | 24 |
| 0.0006 | 25 |
| 0.0502 | 26 |
| 0.0108 | 27 |
| 4.974e-5 | 28 |
| 0.0014 | 29 |
| 0.0072 | 30 |
| 0.0029 | 31 |
| 0.0002 | 32 |
| 0.0003 | 33 |
| 8.211e-6 | 34 |
| 0.0155 | 35 |
| 0.0007 | 36 |
| 0.0031 | 37 |
| 0.0092 | 38 |
| 2.973e-5 | 39 |
| 0.0162 | 40 |
| 0.0195 | 41 |
| 0.0055 | 42 |
| 0.0182 | 43 |
| 0.0054 | 44 |
| 0.0011 | 45 |
| 0.0004 | 46 |
| 0.0026 | 47 |
| 0.0013 | 48 |
| 0.0005 | 49 |
| 0.0010 | 50 |
| 0.0011 | 51 |
| 3.629e-8 | 52 |
| 0.0005 | 53 |
| 0.0328 | 54 |
| 0.0051 | 55 |
| 0.0010 | 56 |
| 0.0201 | 57 |
| 0.0006 | 58 |
| 0.0021 | 59 |
| 0.0963 | 60 |
First 60 of 120 rows.
Assumptions
- Normality of residuals — Shapiro–Wilk W = 0.979, p = .055.
- Constant variance — Breusch–Pagan (Koenker) χ²(2) = 13.05, p = .001; the robust standard errors do not assume it.
- Multicollinearity — Largest VIF 1.01 (x1).
- Linearity — RESET F(1, 116) = 0.37, p = .545.
- Independent residuals — Breusch–Godfrey χ²(4) = 50.14, p < .001; Durbin–Watson = 0.73 (exact p < .001 for positive autocorrelation); rows ordered by t. Consider Newey–West standard errors or an AR(1) error model.
- Influential points — 8 row(s) with Cook's distance above 4/n = 0.033; largest 0.107.
Coefficients
| Term | Estimate | SE (HAC) | t | p | 95% CI low | 95% CI high | β (std.) |
|---|---|---|---|---|---|---|---|
| (Intercept) | 1.440 | 0.3176 | 4.532 | < .001 | 0.8106 | 2.069 | — |
| x1 | 1.031 | 0.0736 | 14.009 | < .001 | 0.8855 | 1.177 | 0.8723 |
| x2 | −0.4579 | 0.1077 | −4.253 | < .001 | −0.6712 | −0.2447 | −0.1557 |
Standard errors: Newey–West HAC (lag 4, rows ordered by t); t tests with 117 df.
Specification and residual tests
| Test | Statistic | Reference | p | A small p suggests |
|---|---|---|---|---|
| Breusch–Pagan (original, assumes normal errors) | 19.617 | χ²(2) | < .001 | Variance changes with the predictors. |
| White (squares and cross-products) | 14.565 | χ²(5) | .012 | Variance changes with the predictors, possibly non-linearly. |
| Goldfeld–Quandt (second half vs first) | 4.289 | F(57, 57) | < .001 | Variance grows along the order (rows ordered by t). |
| Harrison–McCabe (exact) | 0.1890 | — | < .001 | Small shares: the first half has less spread than the second. |
| Durbin–Watson (exact, positive) | 0.7285 | — | < .001 | Neighboring residuals move together (lag 1). |
| Breusch–Godfrey | 50.141 | χ²(4) | < .001 | Residuals correlate with their previous 4 value(s). |
| ARCH LM (Engle) | 30.421 | χ²(4) | < .001 | Large residuals cluster in time (volatility clustering). |
| Harvey–Collier (recursive residuals) | 0.4423 | t(116) | .659 | The relationship bends along the order. |
| Rainbow (central half) | 1.016 | F(60, 57) | .477 | The model fits the middle better than the whole range. |
| Bonferroni outlier (row 26) | 3.076 | t(116) | .314 | The most extreme studentized residual, after a Bonferroni correction for n rows. |
Order-dependent tests use rows ordered by t. Exact p-values assume normal errors (Imhof's method).
Most influential rows (Cook's distance)
| Row | Fitted | Residual | Studentized | Leverage | Cook's D |
|---|---|---|---|---|---|
| 62 | 10.833 | −3.073 | −2.632 | 0.0466 | 0.1074 |
| 60 | 9.432 | −3.424 | −2.934 | 0.0345 | 0.0963 |
| 17 | 10.317 | −2.887 | −2.439 | 0.0277 | 0.0542 |
| 26 | 8.836 | 3.611 | 3.076 | 0.0168 | 0.0502 |
| 66 | 9.946 | −2.940 | −2.480 | 0.0232 | 0.0466 |
| 83 | 9.822 | 2.373 | 1.993 | 0.0323 | 0.0431 |
| 113 | 9.641 | 3.021 | 2.546 | 0.0195 | 0.0410 |
| 112 | 8.782 | 3.312 | 2.801 | 0.0158 | 0.0396 |
| 54 | 6.013 | −1.372 | −1.161 | 0.0682 | 0.0328 |
| 63 | 9.307 | −2.420 | −2.017 | 0.0173 | 0.0233 |
Row numbers count the rows used in the analysis (after missing values were left out).
- Ordinary least squares; categorical predictors use treatment contrasts with the first stored level as reference; Newey–West HAC (lag 4, rows ordered by t) standard errors.
The exact R script · R R version 4.5.1 (2025-06-13)
# Linear regression (OLS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.linear 2.0.1 · spec b5117026c6fbdde7
# Dataset: reg_ts (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/reg_ts.parquet", col_select = c("y", "x1", "x2", "t")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("y", "x1", "x2", "t")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("y", "x1", "x2", "t")) # infinite values stop the run (registry/errors.yaml)
# %% Fit
y <- "y"
predictors <- c("x1", "x2")
conf <- 0.95
interactions <- "none" # none | first-two | all-pairs
se_type <- "HAC" # classical | HC0-HC3 | cluster | HAC
diagnostics <- "full" # standard | full
cluster <- NULL
if (se_type == "cluster" && is.null(cluster)) stop("Cluster-robust standard errors need a cluster column (the Cluster role).")
# Treatment contrasts (R's default for unordered factors): the first stored level is the reference.
intercept <- TRUE
if (!intercept && any(vapply(predictors, function(p) is.factor(df[[p]]), logical(1)))) {
stop("A model without an intercept takes numeric predictors only (a categorical predictor would need every level as a column).")
}
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_rows(nrow(df), length(cs_design_labels(df, predictors, interactions, intercept = intercept)) + 1, "Linear regression") # more rows than coefficients
cs_check_not_constant(df[[y]], y)
if (intercept) {
for (p in predictors) cs_check_not_constant(df[[p]], p) # one value (or one level with data) is no variation
}
fml <- cs_model_formula(y, predictors, interactions, intercept = intercept) # intercept = FALSE: y ~ 0 + ...
fit0 <- lm(fml, data = df)
if (anyNA(coef(fit0))) cs_error("CS_E_COLLINEAR")
X <- model.matrix(fit0)
terms <- cs_design_labels(df, predictors, interactions, intercept = intercept)
stopifnot(length(terms) == ncol(X))
colnames(X) <- terms
n <- nrow(X)
k <- ncol(X)
yv <- df[[y]]
b <- setNames(coef(fit0), terms)
e <- unname(residuals(fit0))
# Order-dependent tests (Durbin-Watson, Breusch-Godfrey, Goldfeld-Quandt, ...) and Newey-West errors
# use the rows sorted by this column (stable); the fit itself does not depend on row order.
order_col <- "t"
ord_idx <- order(df[[order_col]], method = "radix")
hac_lag <- NULL
# Covariance of the coefficients: classical, HC0-HC3 (sandwich::vcovHC formulas) or CR1 (Stata factor)
V <- if (se_type == "classical") {
vcov(fit0)
} else if (se_type == "cluster") {
cs_vcov_cluster(X, e, df[[cluster]])
} else if (se_type == "HAC") {
hac <- cs_hac_cov(X[ord_idx, , drop = FALSE], e[ord_idx], NULL)
hac_lag <- hac$lag
hac$V
} else {
cs_vcov_hc(X, e, se_type)
}
dimnames(V) <- list(terms, terms)
n_clusters <- if (se_type == "cluster") length(unique(df[[cluster]])) else NULL
dfree <- if (se_type == "cluster") n_clusters - 1 else n - k # cluster-robust: t with G - 1 df
se <- sqrt(diag(V))
tval <- b / se
pval <- 2 * pt(abs(tval), dfree, lower.tail = FALSE)
crit <- qt(1 - (1 - conf) / 2, dfree)
beta <- cs_std_beta(X, yv, b)
coefs <- lapply(seq_along(terms), function(j) {
list(term = terms[j], estimate = unname(b[j]), se = unname(se[j]), t = unname(tval[j]), p = unname(pval[j]),
ci_low = unname(b[j] - crit * se[j]), ci_high = unname(b[j] + crit * se[j]),
std_beta = if (terms[j] == "(Intercept)") NULL else unname(beta[terms[j]]))
})
s <- summary(fit0)
r2 <- s$r.squared
adj_r2 <- s$adj.r.squared
slope_idx <- which(terms != "(Intercept)")
wf <- cs_wald_f(b, V, slope_idx) # = the classical F with classical SEs (all coefficients when there is no intercept)
f <- wf[1]
df1 <- wf[2]
df2 <- dfree
f_p <- pf(f, df1, df2, lower.tail = FALSE)
f2 <- if (r2 < 1) r2 / (1 - r2) else Inf # an exact fit has R^2 = 1
sigma <- s$sigma
log_lik <- as.numeric(logLik(fit0))
aic <- -2 * log_lik + 2 * (k + 1) # k coefficients + sigma (= AIC(fit0))
bic <- -2 * log_lik + log(n) * (k + 1)
# %% Assumptions
assumptions <- list()
add_assumption <- function(a) assumptions[[length(assumptions) + 1]] <<- a
sw <- if (n >= 3 && n <= 5000) shapiro.test(e) else NULL
if (!is.null(sw)) {
status <- if (sw$p.value >= 0.05) "pass" else if (n >= 50) "info" else "warn"
add_assumption(list(key = "normality", label = "Normality of residuals", status = status, statistic = unname(sw$statistic), p = sw$p.value,
detail = paste0(sprintf("Shapiro–Wilk W = %.3f, %s", sw$statistic, cs_fmt_p(sw$p.value)),
if (status == "info") " (with large n, judge the Q–Q plot)." else ".")))
}
# Koenker's studentized Breusch-Pagan (n * R^2 of e^2 on X, with a constant even when the model has none)
bp_X <- if (intercept) X else cbind(1, X)
bpt <- cs_breusch_pagan(bp_X, e)
bp <- bpt$statistic
bp_p <- bpt$p
robust <- se_type != "classical"
add_assumption(list(key = "homoscedasticity", label = "Constant variance", status = if (robust) "info" else if (bp_p < 0.05) "warn" else "pass",
statistic = bp, p = bp_p,
detail = paste0(sprintf("Breusch–Pagan (Koenker) χ²(%d) = %.2f, %s", ncol(bp_X) - 1, bp, cs_fmt_p(bp_p)),
if (robust) "; the robust standard errors do not assume it." else if (bp_p < 0.05) "; consider robust (HC3) standard errors." else ".")))
main_cols <- terms[terms != "(Intercept)" & !grepl(" × ", terms, fixed = TRUE)]
vifs <- cs_gvif(X, main_cols, df, predictors) # one generalized VIF per factor
max_vif <- NULL
if (length(vifs)) {
max_vif <- max(vifs)
status <- if (max_vif < 5) "pass" else if (max_vif < 10) "warn" else "fail"
add_assumption(list(key = "multicollinearity", label = "Multicollinearity", status = status, statistic = max_vif,
detail = paste0(sprintf("Largest VIF %.2f (%s)", max_vif, names(vifs)[which.max(vifs)]),
if (length(main_cols) < length(slope_idx)) "; interaction columns are left out (their correlation with main effects is structural)." else ".")))
}
# Ramsey RESET (powers of yhat, or of each numeric predictor) -- not defined when they add nothing
# (e.g. a model that fits every cell mean).
fitted_v <- unname(fitted(fit0))
reset_type <- "fitted"
reset_power <- as.integer(2)
reset_f <- NULL
reset_p <- NULL
reset_df1 <- NULL
reset_df2 <- NULL
reset <- cs_reset_test(X, yv, fitted_v, reset_power, reset_type)
if (!is.null(reset)) {
reset_f <- reset$statistic
reset_p <- reset$p
reset_df1 <- reset$df1
reset_df2 <- reset$df2
add_assumption(list(key = "linearity", label = "Linearity", status = if (reset_p < 0.05) "warn" else "pass", statistic = reset_f, p = reset_p,
detail = paste0(sprintf("RESET F(%d, %d) = %.2f, %s", as.integer(reset_df1), as.integer(reset_df2), reset_f, cs_fmt_p(reset_p)),
if (reset_p < 0.05) "; look for curvature or missing interactions." else ".")))
} else {
add_assumption(list(key = "linearity", label = "Linearity", status = "info",
detail = if (reset_type == "fitted") "RESET does not apply: the model already fits a separate mean for every combination of predictor values."
else "RESET does not apply: no numeric predictor with more than two values to raise to powers."))
}
Xo <- X[ord_idx, , drop = FALSE]
yo <- yv[ord_idx]
eo <- e[ord_idx]
order_note <- if (!is.null(order_col)) sprintf("rows ordered by %s", order_col) else "rows in stored order"
dw <- cs_durbin_watson(eo)
battery <- NULL
if (diagnostics == "full") {
lag_order <- as.integer(4)
battery <- list(bp_classic = cs_bp_classic(X, e), white = cs_white(X, e), gq = cs_goldfeld_quandt(Xo, yo),
hmc = cs_harrison_mccabe(Xo, eo), dw = cs_durbin_watson_exact(Xo, eo), bg = cs_breusch_godfrey(Xo, eo, lag_order),
arch = cs_arch_lm(eo, lag_order), hc = cs_harvey_collier(Xo, yo), rainbow = cs_rainbow(Xo, yo))
}
if (!is.null(battery)) {
bgt <- battery$bg
dwx <- battery$dw
add_assumption(list(key = "independence", label = "Independent residuals", status = if (bgt$p < 0.05) "warn" else "pass", statistic = bgt$statistic, p = bgt$p,
detail = paste0(sprintf("Breusch–Godfrey χ²(%d) = %.2f, %s; Durbin–Watson = %.2f", as.integer(bgt$df), bgt$statistic, cs_fmt_p(bgt$p), dw),
if (!is.null(dwx$p)) sprintf(" (exact %s for positive autocorrelation)", cs_fmt_p(dwx$p)) else "",
sprintf("; %s.", order_note),
if (bgt$p < 0.05) " Consider Newey–West standard errors or an AR(1) error model." else "")))
} else {
add_assumption(list(key = "independence", label = "Independent residuals", status = if (dw < 1.5 || dw > 2.5) "warn" else "info", statistic = dw,
detail = paste0(sprintf("Durbin–Watson = %.2f (≈ 2 when residuals in row order are uncorrelated; ", dw),
if (!is.null(order_col)) sprintf("%s).", order_note) else "only meaningful for ordered rows).")))
}
lev <- unname(hatvalues(fit0))
cooks <- unname(cooks.distance(fit0))
stud <- unname(rstudent(fit0))
std_resid <- unname(rstandard(fit0))
n_influential <- sum(cooks > 4 / n)
max_cooks <- max(cooks)
max_leverage <- max(lev)
add_assumption(list(key = "influence", label = "Influential points", status = if (max_cooks >= 1) "warn" else if (n_influential > 0) "info" else "pass",
statistic = max_cooks,
detail = paste0(sprintf("%d row(s) with Cook's distance above 4/n = %.3f; largest %.3f", n_influential, 4 / n, max_cooks),
if (max_cooks >= 1) " (≥ 1: refit without it to see whether conclusions change)." else ".")))
if (n < 10 * length(slope_idx)) warnings <- c(warnings, sprintf("Fewer than 10 rows per coefficient (%d rows, %d slopes): estimates may be unstable.", n, length(slope_idx)))
if (se_type == "cluster" && n_clusters < 30) {
warnings <- c(warnings, sprintf("Only %d clusters: cluster-robust standard errors can be too small with fewer than 30–50 clusters.", n_clusters))
}
if (!is.null(battery)) battery$outlier <- cs_bonferroni_outlier(stud, n - k - 1)
top <- head(order(-cooks, method = "radix"), 10)
influence_rows <- lapply(top, function(i) list(row = i, fitted = fitted_v[i], residual = e[i], studentized = stud[i], leverage = lev[i], cooks = cooks[i]))
# %% Simple slopes and Johnson-Neyman (first interacting pair with a numeric predictor)
values <- list()
slopes <- NULL
if (interactions != "none" && length(predictors) >= 2) slopes <- cs_simple_slopes(df, predictors, b, V, dfree, conf)
jn <- NULL
if (!is.null(slopes)) {
for (r in slopes$rows) {
values[[sprintf("slope[%s]", r$at)]] <- r$slope
values[[sprintf("slope_se[%s]", r$at)]] <- r$se
values[[sprintf("slope_p[%s]", r$at)]] <- r$p
values[[sprintf("slope_ci_low[%s]", r$at)]] <- r$ci_low
values[[sprintf("slope_ci_high[%s]", r$at)]] <- r$ci_high
}
if (!is.factor(df[[slopes$moderator]])) {
inter <- if (predictors[1] == slopes$focal) paste0(slopes$focal, " × ", slopes$moderator) else paste0(slopes$moderator, " × ", slopes$focal)
m <- df[[slopes$moderator]]
jn <- cs_johnson_neyman(b, V, slopes$focal, inter, dfree, 1 - conf, min(m), max(m))
values$jn_low <- jn$low
values$jn_high <- jn$high
values$jn_region <- jn$region
}
}
# %% Estimated marginal means (categorical predictors)
factors <- predictors[vapply(predictors, function(p) is.factor(df[[p]]), logical(1))]
covariates <- setdiff(predictors, factors)
emm_rows <- list()
pair_rows <- list()
simple_rows <- list()
emm_chart <- NULL
adjust <- "tukey"
if (TRUE && length(factors)) {
for (fac in factors) {
em <- cs_emmeans(fit0, df, fac, factors, covariates, conf = conf, vcov = V, df = dfree)
ct <- cs_emm_contrasts(fit0, df, fac, factors, covariates, adjust = adjust, conf = conf, vcov = V, df = dfree)
for (i in seq_len(nrow(em))) {
emm_rows[[length(emm_rows) + 1]] <- list(factor = fac, level = em$level[i], emm = em$emm[i], se = em$se[i], ci_low = em$ci_low[i], ci_high = em$ci_high[i])
values[[sprintf("emm[%s|%s]", fac, em$level[i])]] <- em$emm[i]
values[[sprintf("emm_se[%s|%s]", fac, em$level[i])]] <- em$se[i]
}
for (i in seq_len(nrow(ct))) {
pair_rows[[length(pair_rows) + 1]] <- list(factor = fac, contrast = ct$contrast[i], estimate = ct$estimate[i], se = ct$se[i], t = ct$t[i],
p_adj = ct$p_adj[i], ci_low = ct$ci_low[i], ci_high = ct$ci_high[i])
values[[sprintf("emm_diff[%s|%s]", fac, ct$contrast[i])]] <- ct$estimate[i]
values[[sprintf("emm_p_adj[%s|%s]", fac, ct$contrast[i])]] <- ct$p_adj[i]
}
}
a <- predictors[1]
bb <- if (length(predictors) > 1) predictors[2] else NULL
if (interactions != "none" && !is.null(bb) && a %in% factors && bb %in% factors) {
# Two interacting factors: EMMs of the first within each level of the second, with simple-effect tests.
em <- cs_emmeans(fit0, df, a, factors, covariates, by = bb, conf = conf, vcov = V, df = dfree)
emm_chart <- cs_chart("emm", "emm-plot", sprintf("Estimated marginal means of %s: %s by %s", y, a, bb), list(
x = cs_col(a, em$level, levels = levels(df[[a]])), mean = cs_col(paste0(y, " (EMM)"), em$emm),
low = cs_col("low", em$ci_low), high = cs_col("high", em$ci_high), trace = cs_col(bb, em$by, levels = levels(df[[bb]]))))
jt <- cs_emm_joint_test(fit0, df, a, factors, covariates, by = bb, vcov = V, df = dfree)
for (i in seq_len(nrow(jt))) {
simple_rows[[length(simple_rows) + 1]] <- list(at = sprintf("%s = %s", bb, jt$by[i]), effect = a, f = jt$f[i], df1 = jt$df1[i], df2 = jt$df2[i], p = jt$p[i])
}
} else {
em <- cs_emmeans(fit0, df, factors[1], factors, covariates, conf = conf, vcov = V, df = dfree)
emm_chart <- cs_chart("emm", "emm-plot", sprintf("Estimated marginal means of %s by %s", y, factors[1]), list(
x = cs_col(factors[1], em$level, levels = levels(df[[factors[1]]])), mean = cs_col(paste0(y, " (EMM)"), em$emm),
low = cs_col("low", em$ci_low), high = cs_col("high", em$ci_high)))
}
}
# %% Result
alpha <- 1 - conf
pct <- sprintf("%.0f%%", conf * 100)
significant <- vapply(Filter(function(cf) cf$term != "(Intercept)" && cf$p < alpha, coefs), `[[`, "", "term")
se_label <- if (se_type == "classical") "classical" else if (se_type == "cluster") sprintf("cluster-robust (CR1, %d clusters)", n_clusters) else if (se_type == "HAC") sprintf("Newey–West HAC (lag %d, %s)", as.integer(hac_lag), order_note) else sprintf("robust (%s)", se_type)
summary <- paste0(
sprintf("The model explains %.0f%% of the variance in %s (adjusted R² = %.2f, F(%.0f, %.0f) = %.2f, %s; n = %d). ",
r2 * 100, y, adj_r2, df1, df2, f, cs_fmt_p(f_p), n),
if (length(significant)) sprintf("Significant terms: %s.", paste(significant, collapse = ", ")) else "No individual term is significant."
)
values <- c(values, list(r_squared = r2, adj_r_squared = adj_r2, f2 = f2, f = f, df1 = df1, df2 = df2, f_p = f_p, sigma = sigma, n = n, k = k,
log_lik = log_lik, aic = aic, bic = bic, bp = bp, bp_p = bp_p, max_vif = max_vif,
sw_p_resid = if (is.null(sw)) NULL else sw$p.value, reset_f = reset_f, reset_p = reset_p, reset_df1 = reset_df1, reset_df2 = reset_df2, dw = dw,
max_cooks = max_cooks, n_influential = n_influential, max_leverage = max_leverage, se_type = se_type,
n_params = k, max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1, missing_share = if (n_input > 0) n_dropped / n_input else 0))
if (se_type == "cluster") values$n_clusters <- n_clusters
if (se_type == "HAC") values$hac_lag <- hac_lag
diag_rows <- list()
if (!is.null(battery)) {
diag <- function(test, bt, key, p_key, df_text, reads) {
if (is.null(bt)) {
diag_rows[[length(diag_rows) + 1]] <<- list(test = test, reads = "Not defined for this design.")
return(invisible())
}
values[[key]] <<- bt$statistic
values[[p_key]] <<- bt$p
diag_rows[[length(diag_rows) + 1]] <<- c(list(test = test, statistic = bt$statistic), if (!is.null(df_text)) list(df = df_text(bt)), list(p = bt$p, reads = reads))
}
diag("Breusch–Pagan (original, assumes normal errors)", battery$bp_classic, "bp_classic", "bp_classic_p", function(b) sprintf("χ²(%d)", as.integer(b$df)), "Variance changes with the predictors.")
diag("White (squares and cross-products)", battery$white, "white", "white_p", function(b) sprintf("χ²(%d)", as.integer(b$df)), "Variance changes with the predictors, possibly non-linearly.")
if (!is.null(battery$white)) values$white_df <- battery$white$df
diag("Goldfeld–Quandt (second half vs first)", battery$gq, "gq_f", "gq_p", function(b) sprintf("F(%d, %d)", as.integer(b$df1), as.integer(b$df2)), sprintf("Variance grows along the order (%s).", order_note))
diag("Harrison–McCabe (exact)", battery$hmc, "hmc", "hmc_p", NULL, "Small shares: the first half has less spread than the second.")
diag("Durbin–Watson (exact, positive)", battery$dw, "dw", "dw_p", NULL, "Neighboring residuals move together (lag 1).")
diag("Breusch–Godfrey", battery$bg, "bg", "bg_p", function(b) sprintf("χ²(%d)", as.integer(b$df)), sprintf("Residuals correlate with their previous %d value(s).", lag_order))
diag("ARCH LM (Engle)", battery$arch, "arch_lm", "arch_p", function(b) sprintf("χ²(%d)", as.integer(b$df)), "Large residuals cluster in time (volatility clustering).")
diag("Harvey–Collier (recursive residuals)", battery$hc, "hc_t", "hc_p", function(b) sprintf("t(%d)", as.integer(b$df)), "The relationship bends along the order.")
diag("Rainbow (central half)", battery$rainbow, "rainbow_f", "rainbow_p", function(b) sprintf("F(%d, %d)", as.integer(b$df1), as.integer(b$df2)), "The model fits the middle better than the whole range.")
ot <- battery$outlier
values$outlier_t <- ot$statistic
values$outlier_p_bonf <- ot$p
values$outlier_row <- ot$row
diag_rows[[length(diag_rows) + 1]] <- list(test = sprintf("Bonferroni outlier (row %d)", as.integer(ot$row)), statistic = ot$statistic, df = sprintf("t(%d)", as.integer(n - k - 1)),
p = ot$p, reads = "The most extreme studentized residual, after a Bonferroni correction for n rows.")
}
standardized <- TRUE
for (cf in coefs) {
for (pair in list(c("coef", "estimate"), c("se", "se"), c("t", "t"), c("p", "p"), c("ci_low", "ci_low"), c("ci_high", "ci_high"))) {
values[[sprintf("%s[%s]", pair[1], cf$term)]] <- cf[[pair[2]]]
}
if (standardized && !is.null(cf$std_beta)) values[[sprintf("std_beta[%s]", cf$term)]] <- cf$std_beta
}
coef_columns <- list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "se", label = if (se_type == "classical") "SE" else sprintf("SE (%s)", se_type), type = "number"),
list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"))
if (standardized) coef_columns[[length(coef_columns) + 1]] <- list(key = "std_beta", label = "β (std.)", type = "number")
coef_rows <- lapply(coefs, function(cf) if (standardized) cf else cf[names(cf) != "std_beta"])
tables <- list(list(key = "coefficients", title = "Coefficients", columns = coef_columns, rows = coef_rows,
note = sprintf("Standard errors: %s; t tests with %s df.", se_label, format(df2))))
if (!is.null(slopes)) {
note <- NULL
if (!is.null(jn)) {
mod <- slopes$moderator
note <- paste0(switch(jn$region,
outside = sprintf("Johnson–Neyman: the slope is significant (α = %s) when %s < %.3f or > %.3f.", format(alpha), mod, jn$low, jn$high),
inside = sprintf("Johnson–Neyman: the slope is significant (α = %s) when %.3f < %s < %.3f.", format(alpha), jn$low, mod, jn$high),
all = sprintf("Johnson–Neyman: the slope is significant at every value of %s.", mod),
none = sprintf("Johnson–Neyman: the slope is not significant at any value of %s.", mod)),
sprintf(" Observed %s: %s to %s.", mod, format(min(df[[mod]])), format(max(df[[mod]]))))
}
tables[[length(tables) + 1]] <- list(key = "simple_slopes", title = sprintf("Simple slopes of %s", slopes$focal), columns = list(
list(key = "at", label = "At", type = "string"), list(key = "slope", label = "Slope", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
rows = lapply(slopes$rows, function(r) r[names(r) != "value"]), note = note)
}
if (length(emm_rows)) {
tables[[length(tables) + 1]] <- list(key = "emm", title = "Estimated marginal means", columns = list(
list(key = "factor", label = "Factor", type = "string"), list(key = "level", label = "Level", type = "string"),
list(key = "emm", label = "EMM", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
rows = emm_rows, note = "Other factors averaged with equal weights; numeric predictors at their means.")
tables[[length(tables) + 1]] <- list(key = "posthoc", title = "Pairwise comparisons of marginal means", columns = list(
list(key = "factor", label = "Factor", type = "string"), list(key = "contrast", label = "Contrast", type = "string"),
list(key = "estimate", label = "Difference", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "t", label = "t", type = "number"), list(key = "p_adj", label = "p (adj.)", type = "pvalue"),
list(key = "ci_low", label = "CI low", type = "number"), list(key = "ci_high", label = "CI high", type = "number")),
rows = pair_rows, note = sprintf("Adjustment: %s (within each factor).", adjust))
}
if (length(simple_rows)) {
tables[[length(tables) + 1]] <- list(key = "simple_effects", title = "Simple effects", columns = list(
list(key = "at", label = "At", type = "string"), list(key = "effect", label = "Effect of", type = "string"),
list(key = "f", label = "F", type = "number"), list(key = "df1", label = "df1", type = "number"),
list(key = "df2", label = "df2", type = "number"), list(key = "p", label = "p", type = "pvalue")), rows = simple_rows)
}
if (length(diag_rows)) {
tables[[length(tables) + 1]] <- list(key = "diagnostics", title = "Specification and residual tests", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
list(key = "df", label = "Reference", type = "string"), list(key = "p", label = "p", type = "pvalue"),
list(key = "reads", label = "A small p suggests", type = "string")),
rows = diag_rows, note = sprintf("Order-dependent tests use %s. Exact p-values assume normal errors (Imhof's method).", order_note))
}
tables[[length(tables) + 1]] <- list(key = "influence", title = "Most influential rows (Cook's distance)", columns = list(
list(key = "row", label = "Row", type = "integer"), list(key = "fitted", label = "Fitted", type = "number"),
list(key = "residual", label = "Residual", type = "number"), list(key = "studentized", label = "Studentized", type = "number"),
list(key = "leverage", label = "Leverage", type = "number"), list(key = "cooks", label = "Cook's D", type = "number")),
rows = influence_rows, note = "Row numbers count the rows used in the analysis (after missing values were left out).")
chart_rows <- unique(round(seq(1, n, length.out = min(n, 5000))))
charts <- list(cs_chart("residuals", "residual-panel", "Residual diagnostics", list(
fitted = cs_col("Fitted", fitted_v[chart_rows]), residual = cs_col("Residual", e[chart_rows]),
stdResidual = cs_col("Standardized residual", std_resid[chart_rows]), leverage = cs_col("Leverage", lev[chart_rows]),
cooks = cs_col("Cook's distance", cooks[chart_rows]))))
if (!is.null(emm_chart)) charts[[length(charts) + 1]] <- emm_chart
# %% Partial-regression charts: what each term adds, whether a numeric term bends, and Cook's distance by row.
panel_cols <- head(which(terms != "(Intercept)"), 9)
panel_rows <- unique(round(seq(1, n, length.out = min(n, 2000))))
row_names <- sprintf("row %d", panel_rows)
resid_on <- function(Z, v) if (ncol(Z)) as.numeric(qr.resid(qr(Z), v)) else as.numeric(v)
if (length(panel_cols)) {
av <- lapply(panel_cols, function(j) {
Z <- X[, -j, drop = FALSE]
list(x = resid_on(Z, X[, j])[panel_rows], y = resid_on(Z, yv)[panel_rows])
})
charts[[length(charts) + 1]] <- cs_chart("added-variable", "added-variable", "Added-variable plots", list(
x_res = cs_col("Predictor given the others", unlist(lapply(av, `[[`, "x")), "numeric"),
y_res = cs_col(sprintf("%s given the others", y), unlist(lapply(av, `[[`, "y")), "numeric"),
term = cs_col("Term", rep(terms[panel_cols], each = length(panel_rows)), "categorical", levels = terms[panel_cols]),
label = cs_col("Row", rep(row_names, length(panel_cols)), "categorical")
), note = if (k - intercept > 9) "The first 9 terms." else NULL)
}
# Component + residual needs a term that is one numeric column with no interaction to share its effect.
cr_cols <- if (interactions == "none") panel_cols[terms[panel_cols] %in% predictors] else integer(0)
if (length(cr_cols)) {
charts[[length(charts) + 1]] <- cs_chart("component-residual", "component-residual", "Component + residual plots", list(
x = cs_col("Predictor", unlist(lapply(cr_cols, function(j) X[panel_rows, j]), use.names = FALSE), "numeric"),
partial = cs_col("Component + residual", unlist(lapply(cr_cols, function(j) e[panel_rows] + b[[j]] * X[panel_rows, j]), use.names = FALSE), "numeric"),
term = cs_col("Term", rep(terms[cr_cols], each = length(panel_rows)), "categorical", levels = terms[cr_cols]),
label = cs_col("Row", rep(row_names, length(cr_cols)), "categorical")
))
}
charts[[length(charts) + 1]] <- cs_chart("influence-index", "influence-index", "Cook's distance by row", list(
cooks = cs_col("Cook's distance", cooks[chart_rows], "numeric"), index = cs_col("Row", as.numeric(chart_rows), "numeric")
))
cs_publish(list(
method = "regression.linear",
methodVersion = "2.0.1",
title = "Linear regression (OLS)",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("R² = %s, adjusted R² = %s, F(%.0f, %.0f) = %s, %s", cs_fmt_num(r2, leading_zero = FALSE), cs_fmt_num(adj_r2, leading_zero = FALSE),
df1, df2, cs_fmt_num(f), cs_fmt_p(f_p)),
statistics = list(
list(key = "r_squared", label = "R²", value = r2), list(key = "adj_r_squared", label = "Adjusted R²", value = adj_r2),
list(key = "f", label = "F", value = f), list(key = "f_p", label = "p (F test)", value = f_p, format = "p"),
list(key = "sigma", label = "Residual SE", value = sigma), list(key = "aic", label = "AIC", value = aic)
),
tables = tables,
effectSizes = list(list(key = "f2", label = "Cohen's f²", value = f2, method = "R² / (1 − R²)"),
list(key = "r_squared", label = "R²", value = r2, method = "1 − SSres / SStot")),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0("Ordinary least squares; categorical predictors use treatment contrasts with the first stored level as reference; ", se_label, " standard errors.",
if (interactions != "none") " With interactions, main effects are conditional on the other predictor being 0 (or at its reference level)." else "")),
charts = charts,
values = values
))
R² = .81, adjusted R² = .80, F(2, 117) = 100.41, p < .001
- R²
- 0.8071
- Adjusted R²
- 0.8038
- F
- 100.41
- p (F test)
- < .001
- Residual SE
- 1.226
- AIC
- 394.39
Effect size
- Cohen's f² 4.183
- R² 0.8071
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality of residuals — Shapiro–Wilk W = 0.979, p = .055.
- Constant variance — Breusch–Pagan (Koenker) χ²(2) = 13.05, p = .001; the robust standard errors do not assume it.
- Multicollinearity — Largest VIF 1.01 (x1).
- Linearity — RESET F(1, 116) = 0.37, p = .545.
- Independent residuals — Breusch–Godfrey χ²(4) = 50.14, p < .001; Durbin–Watson = 0.73 (exact p < .001 for positive autocorrelation); rows ordered by t. Consider Newey–West standard errors or an AR(1) error model.
- Influential points — 8 row(s) with Cook's distance above 4/n = 0.033; largest 0.107.
Coefficients
| Term | Estimate | SE (HAC) | t | p | 95% CI low | 95% CI high | β (std.) |
|---|---|---|---|---|---|---|---|
| (Intercept) | 1.440 | 0.3176 | 4.532 | < .001 | 0.8106 | 2.069 | — |
| x1 | 1.031 | 0.0736 | 14.009 | < .001 | 0.8855 | 1.177 | 0.8723 |
| x2 | −0.4579 | 0.1077 | −4.253 | < .001 | −0.6712 | −0.2447 | −0.1557 |
Standard errors: Newey–West HAC (lag 4, rows ordered by t); t tests with 117 df.
Specification and residual tests
| Test | Statistic | Reference | p | A small p suggests |
|---|---|---|---|---|
| Breusch–Pagan (original, assumes normal errors) | 19.617 | χ²(2) | < .001 | Variance changes with the predictors. |
| White (squares and cross-products) | 14.565 | χ²(5) | .012 | Variance changes with the predictors, possibly non-linearly. |
| Goldfeld–Quandt (second half vs first) | 4.289 | F(57, 57) | < .001 | Variance grows along the order (rows ordered by t). |
| Harrison–McCabe (exact) | 0.1890 | — | < .001 | Small shares: the first half has less spread than the second. |
| Durbin–Watson (exact, positive) | 0.7285 | — | < .001 | Neighboring residuals move together (lag 1). |
| Breusch–Godfrey | 50.141 | χ²(4) | < .001 | Residuals correlate with their previous 4 value(s). |
| ARCH LM (Engle) | 30.421 | χ²(4) | < .001 | Large residuals cluster in time (volatility clustering). |
| Harvey–Collier (recursive residuals) | 0.4423 | t(116) | .659 | The relationship bends along the order. |
| Rainbow (central half) | 1.016 | F(60, 57) | .477 | The model fits the middle better than the whole range. |
| Bonferroni outlier (row 26) | 3.076 | t(116) | .314 | The most extreme studentized residual, after a Bonferroni correction for n rows. |
Order-dependent tests use rows ordered by t. Exact p-values assume normal errors (Imhof's method).
Most influential rows (Cook's distance)
| Row | Fitted | Residual | Studentized | Leverage | Cook's D |
|---|---|---|---|---|---|
| 62 | 10.833 | −3.073 | −2.632 | 0.0466 | 0.1074 |
| 60 | 9.432 | −3.424 | −2.934 | 0.0345 | 0.0963 |
| 17 | 10.317 | −2.887 | −2.439 | 0.0277 | 0.0542 |
| 26 | 8.836 | 3.611 | 3.076 | 0.0168 | 0.0502 |
| 66 | 9.946 | −2.940 | −2.480 | 0.0232 | 0.0466 |
| 83 | 9.822 | 2.373 | 1.993 | 0.0323 | 0.0431 |
| 113 | 9.641 | 3.021 | 2.546 | 0.0195 | 0.0410 |
| 112 | 8.782 | 3.312 | 2.801 | 0.0158 | 0.0396 |
| 54 | 6.013 | −1.372 | −1.161 | 0.0682 | 0.0328 |
| 63 | 9.307 | −2.420 | −2.017 | 0.0173 | 0.0233 |
Row numbers count the rows used in the analysis (after missing values were left out).
- Ordinary least squares; categorical predictors use treatment contrasts with the first stored level as reference; Newey–West HAC (lag 4, rows ordered by t) standard errors.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Linear regression (OLS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.linear 2.0.1 · spec b5117026c6fbdde7
# Dataset: reg_ts (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 statsmodels.api as sm
import statsmodels.formula.api as smf
from scipy import linalg, stats
from statsmodels.stats.diagnostic import het_breuschpagan
from statsmodels.stats.outliers_influence import OLSInfluence
from statsmodels.stats.stattools import durbin_watson
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import emm as csemm
from codesplash.stats import regdiag as rd
from codesplash.stats import regression as csreg
# %% Data
df = pd.read_parquet("tests/parity/fixtures/reg_ts.parquet", columns=["y", "x1", "x2", "t"])
n_input = len(df)
df = df.dropna(subset=["y", "x1", "x2", "t"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["y", "x1", "x2", "t"]) # infinite values stop the run (registry/errors.yaml)
# %% Design matrix
y = "y"
predictors = ["x1", "x2"]
conf = 0.95
interactions = "none" # none | first-two | all-pairs
se_type = "HAC" # classical | HC0–HC3 | cluster | HAC
diagnostics = "full" # standard | full
cluster = None
if se_type == "cluster" and cluster is None:
raise ValueError("Cluster-robust standard errors need a cluster column (the Cluster role).")
# Treatment contrasts: the first stored level of each categorical predictor is the reference (R's default);
# interaction columns in R's model.matrix order.
intercept = True
if not intercept and any(isinstance(df[p].dtype, pd.CategoricalDtype) for p in predictors):
raise ValueError("A model without an intercept takes numeric predictors only (a categorical predictor would need every level as a column).")
X = csreg.design_matrix(df, predictors, interactions, intercept=intercept)
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
cs.check_rows(len(df), X.shape[1] + 1, "Linear regression") # more rows than coefficients
check_not_constant(df[y], y)
if intercept:
for p in predictors:
check_not_constant(df[p], p) # one value (or one level with data) is no variation
if np.linalg.matrix_rank(X.to_numpy()) < X.shape[1]:
cs.cs_error("CS_E_COLLINEAR")
n, k = X.shape
yv = df[y].to_numpy(dtype=float)
terms = list(X.columns)
# Order-dependent tests (Durbin–Watson, Breusch–Godfrey, Goldfeld–Quandt, …) and Newey–West errors
# use the rows sorted by this column (stable); the fit itself does not depend on row order.
order_col = "t"
ord_idx = np.argsort(df[order_col].to_numpy(), kind="stable")
# %% Fit
model = sm.OLS(yv, X)
fit0 = model.fit(method="qr") # classical fit (QR, like R's lm): R², residuals, diagnostics
if se_type in ("classical", "HAC"):
fit = fit0
elif se_type == "cluster":
groups = pd.factorize(df[cluster].astype(str))[0]
fit = model.fit(method="qr", cov_type="cluster", cov_kwds={"groups": groups}, use_t=True) # CR1: G/(G−1)·(n−1)/(n−k)
else:
fit = model.fit(method="qr", cov_type=se_type, use_t=True)
if se_type == "classical":
# σ²·R⁻¹R⁻ᵀ from the QR factor (as R's chol2inv): inverting X'X would square its condition number
r_inv = linalg.solve_triangular(np.linalg.qr(X.to_numpy(), mode="r"), np.eye(k))
V = fit0.scale * (r_inv @ r_inv.T)
elif se_type == "HAC":
V, hac_lag = rd.hac_cov(X.to_numpy()[ord_idx], np.asarray(fit0.resid)[ord_idx], None)
else:
V = np.asarray(fit.cov_params())
b = fit0.params.to_numpy()
n_clusters = int(df[cluster].nunique()) if se_type == "cluster" else None
dfree = float(n_clusters - 1) if se_type == "cluster" else float(n - k) # cluster-robust: t with G − 1 df
se = np.sqrt(np.diag(V))
tval = b / se
pval = 2 * stats.t.sf(np.abs(tval), dfree)
crit = stats.t.ppf(1 - (1 - conf) / 2, dfree)
beta = csreg.std_beta(X, yv, b)
coefs = [
{"term": term, "estimate": float(b[j]), "se": float(se[j]), "t": float(tval[j]), "p": float(pval[j]),
"ci_low": float(b[j] - crit * se[j]), "ci_high": float(b[j] + crit * se[j]), "std_beta": beta.get(term)}
for j, term in enumerate(terms)
]
r2, adj_r2 = float(fit0.rsquared), float(fit0.rsquared_adj)
slope_idx = [j for j, term in enumerate(terms) if term != "(Intercept)"]
f, df1 = csreg.wald_f(b, V, slope_idx) # = the classical F with classical SEs (all coefficients when there is no intercept)
df1, df2 = float(df1), dfree
f_p = float(stats.f.sf(f, df1, df2))
f2 = r2 / (1 - r2) if r2 < 1 else float("inf") # an exact fit has R² = 1
sigma = float(np.sqrt(fit0.scale))
log_lik = float(fit0.llf)
aic = -2 * log_lik + 2 * (k + 1) # pinned: k coefficients + σ (R's AIC; statsmodels' .aic omits σ)
bic = -2 * log_lik + np.log(n) * (k + 1)
# %% Assumptions
assumptions = []
resid = np.asarray(fit0.resid)
fitted = np.asarray(fit0.fittedvalues)
sw = stats.shapiro(resid) if 3 <= n <= 5000 else None
if sw is not None:
status = "pass" if sw.pvalue >= 0.05 else ("info" if n >= 50 else "warn")
assumptions.append({"key": "normality", "label": "Normality of residuals", "status": status, "statistic": float(sw.statistic), "p": float(sw.pvalue),
"detail": f"Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)}" + (" (with large n, judge the Q–Q plot)." if status == "info" else ".")})
# Koenker's studentized Breusch–Pagan (n·R² of e² on X, with a constant even when the model has none)
bp_X = X.to_numpy() if intercept else np.column_stack([np.ones(n), X.to_numpy()])
bp, bp_p, _, _ = het_breuschpagan(resid, bp_X)
robust = se_type != "classical"
assumptions.append({"key": "homoscedasticity", "label": "Constant variance", "status": "info" if robust else ("warn" if bp_p < 0.05 else "pass"),
"statistic": float(bp), "p": float(bp_p),
"detail": f"Breusch–Pagan (Koenker) χ²({bp_X.shape[1] - 1}) = {bp:.2f}, {cs.fmt_p(bp_p)}"
+ ("; the robust standard errors do not assume it." if robust else ("; consider robust (HC3) standard errors." if bp_p < 0.05 else "."))})
main_cols = [c for c in terms if c != "(Intercept)" and csreg.TIMES not in c]
vifs = csreg.gvif(X, main_cols, df, predictors) # one generalized VIF per factor
max_vif = None
if vifs:
worst = max(vifs, key=vifs.get)
max_vif = vifs[worst]
status = "pass" if max_vif < 5 else ("warn" if max_vif < 10 else "fail")
assumptions.append({"key": "multicollinearity", "label": "Multicollinearity", "status": status, "statistic": max_vif,
"detail": f"Largest VIF {max_vif:.2f} ({worst})" + ("; interaction columns are left out (their correlation with main effects is structural)." if len(main_cols) < len(slope_idx) else ".")})
# Ramsey RESET (powers of ŷ, or of each numeric predictor) — not defined when they add nothing
# (e.g. a model that fits every cell mean).
reset_type = "fitted"
reset_power = int(2)
reset = rd.reset(X.to_numpy(), yv, fitted, reset_power, reset_type)
if reset is not None:
reset_f, reset_p, reset_df1, reset_df2 = reset["statistic"], reset["p"], reset["df1"], reset["df2"]
assumptions.append({"key": "linearity", "label": "Linearity", "status": "warn" if reset_p < 0.05 else "pass", "statistic": reset_f, "p": reset_p,
"detail": f"RESET F({reset_df1}, {reset_df2}) = {reset_f:.2f}, {cs.fmt_p(reset_p)}" + ("; look for curvature or missing interactions." if reset_p < 0.05 else ".")})
else:
reset_f = reset_p = reset_df1 = reset_df2 = None
assumptions.append({"key": "linearity", "label": "Linearity", "status": "info",
"detail": "RESET does not apply: the model already fits a separate mean for every combination of predictor values." if reset_type == "fitted"
else "RESET does not apply: no numeric predictor with more than two values to raise to powers."})
Xo, yo, eo = X.to_numpy()[ord_idx], yv[ord_idx], resid[ord_idx]
order_note = f"rows ordered by {order_col}" if order_col else "rows in stored order"
dw = float(durbin_watson(eo))
battery = {}
if diagnostics == "full":
lag_order = int(4)
battery = {"bp_classic": rd.bp_classic(X.to_numpy(), resid), "white": rd.white(X.to_numpy(), resid), "gq": rd.goldfeld_quandt(Xo, yo),
"hmc": rd.harrison_mccabe(Xo, eo), "dw": rd.durbin_watson_exact(Xo, eo), "bg": rd.breusch_godfrey(Xo, eo, lag_order),
"arch": rd.arch_lm(eo, lag_order), "hc": rd.harvey_collier(Xo, yo), "rainbow": rd.rainbow(Xo, yo)}
if battery:
bg, dwx = battery["bg"], battery["dw"]
assumptions.append({"key": "independence", "label": "Independent residuals", "status": "warn" if bg["p"] < 0.05 else "pass", "statistic": bg["statistic"], "p": bg["p"],
"detail": f"Breusch–Godfrey χ²({bg['df']}) = {bg['statistic']:.2f}, {cs.fmt_p(bg['p'])}; Durbin–Watson = {dw:.2f}"
+ (f" (exact {cs.fmt_p(dwx['p'])} for positive autocorrelation)" if dwx["p"] is not None else "") + f"; {order_note}."
+ (" Consider Newey–West standard errors or an AR(1) error model." if bg["p"] < 0.05 else "")})
else:
assumptions.append({"key": "independence", "label": "Independent residuals", "status": "warn" if dw < 1.5 or dw > 2.5 else "info", "statistic": dw,
"detail": f"Durbin–Watson = {dw:.2f} (≈ 2 when residuals in row order are uncorrelated; " + (f"{order_note})." if order_col else "only meaningful for ordered rows).")})
infl = OLSInfluence(fit0)
lev = np.asarray(infl.hat_matrix_diag)
cooks = np.asarray(infl.cooks_distance[0])
stud = np.asarray(infl.resid_studentized_external)
std_resid = np.asarray(infl.resid_studentized_internal)
n_influential = int(np.sum(cooks > 4 / n))
max_cooks, max_leverage = float(cooks.max()), float(lev.max())
assumptions.append({"key": "influence", "label": "Influential points", "status": "warn" if max_cooks >= 1 else ("info" if n_influential else "pass"), "statistic": max_cooks,
"detail": f"{n_influential} row(s) with Cook's distance above 4/n = {4 / n:.3f}; largest {max_cooks:.3f}"
+ (" (≥ 1: refit without it to see whether conclusions change)." if max_cooks >= 1 else ".")})
if n < 10 * len(slope_idx):
warnings.append(f"Fewer than 10 rows per coefficient ({n} rows, {len(slope_idx)} slopes): estimates may be unstable.")
if se_type == "cluster" and n_clusters < 30:
warnings.append(f"Only {n_clusters} clusters: cluster-robust standard errors can be too small with fewer than 30–50 clusters.")
if battery:
battery["outlier"] = rd.bonferroni_outlier(stud, n - k - 1)
top = np.argsort(-cooks, kind="stable")[: min(10, n)]
influence_rows = [{"row": int(i + 1), "fitted": float(fitted[i]), "residual": float(resid[i]), "studentized": float(stud[i]),
"leverage": float(lev[i]), "cooks": float(cooks[i])} for i in top]
# %% Simple slopes and Johnson–Neyman (first interacting pair with a numeric predictor)
values = {}
slopes = None
coef_s = pd.Series(b, index=terms)
cov_s = pd.DataFrame(V, index=terms, columns=terms)
if interactions != "none" and len(predictors) >= 2:
slopes = csreg.simple_slopes(df, predictors, coef_s, cov_s, dfree, conf)
if slopes is not None:
focal, moderator, slope_rows = slopes
for r in slope_rows:
values.update({f"slope[{r['at']}]": r["slope"], f"slope_se[{r['at']}]": r["se"], f"slope_p[{r['at']}]": r["p"],
f"slope_ci_low[{r['at']}]": r["ci_low"], f"slope_ci_high[{r['at']}]": r["ci_high"]})
if not isinstance(df[moderator].dtype, pd.CategoricalDtype):
inter = f"{focal}{csreg.TIMES}{moderator}" if predictors[0] == focal else f"{moderator}{csreg.TIMES}{focal}"
m = df[moderator].to_numpy(dtype=float)
jn = csreg.johnson_neyman(coef_s, cov_s, focal, inter, dfree, 1 - conf, float(m.min()), float(m.max()))
values.update({k2: v for k2, v in (("jn_low", jn["low"]), ("jn_high", jn["high"]), ("jn_region", jn["region"])) if v is not None})
# %% Estimated marginal means (categorical predictors)
factors = [p for p in predictors if isinstance(df[p].dtype, pd.CategoricalDtype)]
covariates = [p for p in predictors if p not in factors]
emm_rows, pair_rows, simple_rows = [], [], []
emm_chart = None
if True and factors:
# The same model through the formula API (EMMs need its design info); estimates are identical.
# Newey–West: refit on the rows in time order (statsmodels' HAC with the n/(n − k) factor = rd.hac_cov).
ffit = smf.ols(csreg.patsy_formula(y, predictors, interactions), data=df.iloc[ord_idx] if se_type == "HAC" else df)
ffit = ffit.fit() if se_type == "classical" else (
ffit.fit(cov_type="cluster", cov_kwds={"groups": pd.factorize(df[cluster].astype(str))[0]}, use_t=True) if se_type == "cluster"
else ffit.fit(cov_type="HAC", cov_kwds={"maxlags": hac_lag, "use_correction": True}, use_t=True) if se_type == "HAC"
else ffit.fit(cov_type=se_type, use_t=True))
adjust = "tukey"
for fac in factors:
em = csemm.emmeans(ffit, df, fac, factors, covariates, conf=conf, df=dfree)
ct = csemm.contrasts(ffit, df, fac, factors, covariates, adjust=adjust, conf=conf, df=dfree)
for _, r in em.iterrows():
emm_rows.append({"factor": fac, "level": str(r["level"]), "emm": float(r["emm"]), "se": float(r["se"]),
"ci_low": float(r["ci_low"]), "ci_high": float(r["ci_high"])})
values[f"emm[{fac}|{r['level']}]"] = float(r["emm"])
values[f"emm_se[{fac}|{r['level']}]"] = float(r["se"])
for _, r in ct.iterrows():
pair_rows.append({"factor": fac, "contrast": str(r["contrast"]), "estimate": float(r["estimate"]), "se": float(r["se"]),
"t": float(r["t"]), "p_adj": float(r["p_adj"]), "ci_low": float(r["ci_low"]), "ci_high": float(r["ci_high"])})
values[f"emm_diff[{fac}|{r['contrast']}]"] = float(r["estimate"])
values[f"emm_p_adj[{fac}|{r['contrast']}]"] = float(r["p_adj"])
# Two interacting factors: EMMs of the first within each level of the second, with simple-effect tests.
a, bb = predictors[0], predictors[1] if len(predictors) > 1 else None
if interactions != "none" and bb is not None and a in factors and bb in factors:
em = csemm.emmeans(ffit, df, a, factors, covariates, by=bb, conf=conf, df=dfree)
emm_chart = cs.chart("emm", "emm-plot", f"Estimated marginal means of {y}: {a} by {bb}", {
"x": cs.col(a, em["level"].astype(str).to_numpy(), levels=[str(x) for x in df[a].cat.categories]),
"mean": cs.col(f"{y} (EMM)", em["emm"].to_numpy()), "low": cs.col("low", em["ci_low"].to_numpy()),
"high": cs.col("high", em["ci_high"].to_numpy()),
"trace": cs.col(bb, em["by"].astype(str).to_numpy(), levels=[str(x) for x in df[bb].cat.categories])})
jt = csemm.joint_test(ffit, df, a, factors, covariates, by=bb, df=dfree)
for _, r in jt.iterrows():
simple_rows.append({"at": f"{bb} = {r['by']}", "effect": a, "f": float(r["f"]), "df1": float(r["df1"]), "df2": float(r["df2"]), "p": float(r["p"])})
elif factors:
em = csemm.emmeans(ffit, df, factors[0], factors, covariates, conf=conf, df=dfree)
emm_chart = cs.chart("emm", "emm-plot", f"Estimated marginal means of {y} by {factors[0]}", {
"x": cs.col(factors[0], em["level"].astype(str).to_numpy(), levels=[str(x) for x in df[factors[0]].cat.categories]),
"mean": cs.col(f"{y} (EMM)", em["emm"].to_numpy()), "low": cs.col("low", em["ci_low"].to_numpy()),
"high": cs.col("high", em["ci_high"].to_numpy())})
# %% Result
alpha = 1 - conf
significant = [c["term"] for c in coefs if c["term"] != "(Intercept)" and c["p"] < alpha]
se_label = {"classical": "classical", "cluster": f"cluster-robust (CR1, {n_clusters} clusters)",
"HAC": f"Newey–West HAC (lag {hac_lag if se_type == 'HAC' else 0}, {order_note})"}.get(se_type, f"robust ({se_type})")
summary = (
f"The model explains {r2:.0%} of the variance in {y} (adjusted R² = {adj_r2:.2f}, F({df1:.0f}, {df2:.0f}) = {f:.2f}, {cs.fmt_p(f_p)}; n = {n}). "
+ (f"Significant terms: {', '.join(significant)}." if significant else "No individual term is significant.")
)
values.update({"r_squared": r2, "adj_r_squared": adj_r2, "f2": f2, "f": f, "df1": df1, "df2": df2, "f_p": f_p, "sigma": sigma,
"n": n, "k": k, "log_lik": log_lik, "aic": aic, "bic": bic, "bp": float(bp), "bp_p": float(bp_p), "max_vif": max_vif,
"sw_p_resid": None if sw is None else float(sw.pvalue), "reset_f": reset_f, "reset_p": reset_p, "dw": dw,
"max_cooks": max_cooks, "n_influential": n_influential, "max_leverage": max_leverage, "se_type": se_type,
"n_params": k, "max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1, "missing_share": n_dropped / n_input if n_input else 0.0})
if se_type == "cluster":
values["n_clusters"] = n_clusters
if se_type == "HAC":
values["hac_lag"] = hac_lag
values.update({"reset_df1": reset_df1, "reset_df2": reset_df2})
diag_rows = []
if battery:
bt = battery
def diag(test, b, stat_key, key, p_key, df_text, reads):
if b is None:
diag_rows.append({"test": test, "statistic": None, "df": None, "p": None, "reads": "Not defined for this design."})
return
values[key] = b["statistic"]
values[p_key] = b["p"]
diag_rows.append({"test": test, "statistic": b["statistic"], "df": df_text(b) if df_text else None, "p": b["p"], "reads": reads})
diag("Breusch–Pagan (original, assumes normal errors)", bt["bp_classic"], "statistic", "bp_classic", "bp_classic_p", lambda b: f"χ²({b['df']})", "Variance changes with the predictors.")
diag("White (squares and cross-products)", bt["white"], "statistic", "white", "white_p", lambda b: f"χ²({b['df']})", "Variance changes with the predictors, possibly non-linearly.")
if bt["white"] is not None:
values["white_df"] = bt["white"]["df"]
diag("Goldfeld–Quandt (second half vs first)", bt["gq"], "statistic", "gq_f", "gq_p", lambda b: f"F({b['df1']}, {b['df2']})", f"Variance grows along the order ({order_note}).")
diag("Harrison–McCabe (exact)", bt["hmc"], "statistic", "hmc", "hmc_p", None, "Small shares: the first half has less spread than the second.")
diag("Durbin–Watson (exact, positive)", bt["dw"], "statistic", "dw", "dw_p", None, "Neighboring residuals move together (lag 1).")
diag("Breusch–Godfrey", bt["bg"], "statistic", "bg", "bg_p", lambda b: f"χ²({b['df']})", f"Residuals correlate with their previous {lag_order} value(s).")
diag("ARCH LM (Engle)", bt["arch"], "statistic", "arch_lm", "arch_p", lambda b: f"χ²({b['df']})", "Large residuals cluster in time (volatility clustering).")
diag("Harvey–Collier (recursive residuals)", bt["hc"], "statistic", "hc_t", "hc_p", lambda b: f"t({b['df']})", "The relationship bends along the order.")
diag("Rainbow (central half)", bt["rainbow"], "statistic", "rainbow_f", "rainbow_p", lambda b: f"F({b['df1']}, {b['df2']})", "The model fits the middle better than the whole range.")
ot = bt["outlier"]
values.update({"outlier_t": ot["statistic"], "outlier_p_bonf": ot["p"], "outlier_row": ot["row"]})
diag_rows.append({"test": f"Bonferroni outlier (row {ot['row']})", "statistic": ot["statistic"], "df": f"t({n - k - 1})", "p": ot["p"],
"reads": "The most extreme studentized residual, after a Bonferroni correction for n rows."})
for c in coefs:
values.update({f"{key}[{c['term']}]": c[key2] for key, key2 in
(("coef", "estimate"), ("se", "se"), ("t", "t"), ("p", "p"), ("ci_low", "ci_low"), ("ci_high", "ci_high"))})
if True and c["std_beta"] is not None:
values[f"std_beta[{c['term']}]"] = c["std_beta"]
pct = f"{conf:.0%}"
coef_columns = [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE" if se_type == "classical" else f"SE ({se_type})", "type": "number"},
{"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}]
if True:
coef_columns.append({"key": "std_beta", "label": "β (std.)", "type": "number"})
tables = [{"key": "coefficients", "title": "Coefficients", "columns": coef_columns,
"rows": [{k2: v for k2, v in c.items() if k2 != "std_beta" or True} for c in coefs],
"note": f"Standard errors: {se_label}; t tests with {df2:g} df."}]
if slopes is not None:
tables.append({"key": "simple_slopes", "title": f"Simple slopes of {slopes[0]}", "columns": [
{"key": "at", "label": "At", "type": "string"}, {"key": "slope", "label": "Slope", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": [{k2: v for k2, v in r.items() if k2 != "value"} for r in slopes[2]],
"note": None if values.get("jn_region") is None else (
{"outside": f"Johnson–Neyman: the slope is significant (α = {alpha:g}) when {slopes[1]} < {values['jn_low']:.3f} or > {values['jn_high']:.3f}.",
"inside": f"Johnson–Neyman: the slope is significant (α = {alpha:g}) when {values['jn_low']:.3f} < {slopes[1]} < {values['jn_high']:.3f}.",
"all": f"Johnson–Neyman: the slope is significant at every value of {slopes[1]}.",
"none": f"Johnson–Neyman: the slope is not significant at any value of {slopes[1]}."}[values["jn_region"]]
+ f" Observed {slopes[1]}: {float(df[slopes[1]].min()):g} to {float(df[slopes[1]].max()):g}.")})
if emm_rows:
tables.append({"key": "emm", "title": "Estimated marginal means", "columns": [
{"key": "factor", "label": "Factor", "type": "string"}, {"key": "level", "label": "Level", "type": "string"},
{"key": "emm", "label": "EMM", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": emm_rows, "note": "Other factors averaged with equal weights; numeric predictors at their means."})
tables.append({"key": "posthoc", "title": "Pairwise comparisons of marginal means", "columns": [
{"key": "factor", "label": "Factor", "type": "string"}, {"key": "contrast", "label": "Contrast", "type": "string"},
{"key": "estimate", "label": "Difference", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "t", "label": "t", "type": "number"}, {"key": "p_adj", "label": "p (adj.)", "type": "pvalue"},
{"key": "ci_low", "label": "CI low", "type": "number"}, {"key": "ci_high", "label": "CI high", "type": "number"}],
"rows": pair_rows, "note": f"Adjustment: {adjust} (within each factor)."})
if simple_rows:
tables.append({"key": "simple_effects", "title": "Simple effects", "columns": [
{"key": "at", "label": "At", "type": "string"}, {"key": "effect", "label": "Effect of", "type": "string"},
{"key": "f", "label": "F", "type": "number"}, {"key": "df1", "label": "df1", "type": "number"},
{"key": "df2", "label": "df2", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}], "rows": simple_rows})
if diag_rows:
tables.append({"key": "diagnostics", "title": "Specification and residual tests", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
{"key": "df", "label": "Reference", "type": "string"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "reads", "label": "A small p suggests", "type": "string"}],
"rows": diag_rows, "note": f"Order-dependent tests use {order_note}. Exact p-values assume normal errors (Imhof's method)."})
tables.append({"key": "influence", "title": "Most influential rows (Cook's distance)", "columns": [
{"key": "row", "label": "Row", "type": "integer"}, {"key": "fitted", "label": "Fitted", "type": "number"},
{"key": "residual", "label": "Residual", "type": "number"}, {"key": "studentized", "label": "Studentized", "type": "number"},
{"key": "leverage", "label": "Leverage", "type": "number"}, {"key": "cooks", "label": "Cook's D", "type": "number"}],
"rows": influence_rows, "note": "Row numbers count the rows used in the analysis (after missing values were left out)."})
chart_rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
charts = [cs.chart("residuals", "residual-panel", "Residual diagnostics", {
"fitted": cs.col("Fitted", fitted[chart_rows]), "residual": cs.col("Residual", resid[chart_rows]),
"stdResidual": cs.col("Standardized residual", np.asarray(std_resid)[chart_rows]),
"leverage": cs.col("Leverage", np.asarray(lev)[chart_rows]), "cooks": cs.col("Cook's distance", np.asarray(cooks)[chart_rows])})]
if emm_chart is not None:
charts.append(emm_chart)
# %% Partial-regression charts: what each term adds, whether a numeric term bends, and Cook's distance by row.
Xm = X.to_numpy()
panel_cols = [j for j, t in enumerate(terms) if t != "(Intercept)"][:9]
panel_rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 2000))).astype(int))
row_names = [f"row {i + 1}" for i in panel_rows]
def resid_on(Z, v):
return v - Z @ np.linalg.lstsq(Z, v, rcond=None)[0] if Z.shape[1] else v
av_x, av_y, av_term, av_label = [], [], [], []
for j in panel_cols:
Z = np.delete(Xm, j, axis=1)
av_x += resid_on(Z, Xm[:, j])[panel_rows].tolist()
av_y += resid_on(Z, yv)[panel_rows].tolist()
av_term += [terms[j]] * len(panel_rows)
av_label += row_names
if panel_cols:
charts.append(cs.chart("added-variable", "added-variable", "Added-variable plots", {
"x_res": cs.col("Predictor given the others", av_x, "numeric"), "y_res": cs.col(f"{y} given the others", av_y, "numeric"),
"term": cs.col("Term", av_term, "categorical", levels=[terms[j] for j in panel_cols]), "label": cs.col("Row", av_label, "categorical"),
}, note=None if k - intercept <= 9 else "The first 9 terms."))
# Component + residual needs a term that is one numeric column with no interaction to share its effect.
cr_cols = [j for j in panel_cols if terms[j] in predictors] if interactions == "none" else []
if cr_cols:
cr_x, cr_y, cr_term, cr_label = [], [], [], []
b_hat = np.asarray(fit0.params)
for j in cr_cols:
cr_x += Xm[panel_rows, j].tolist()
cr_y += (resid[panel_rows] + b_hat[j] * Xm[panel_rows, j]).tolist()
cr_term += [terms[j]] * len(panel_rows)
cr_label += row_names
charts.append(cs.chart("component-residual", "component-residual", "Component + residual plots", {
"x": cs.col("Predictor", cr_x, "numeric"), "partial": cs.col("Component + residual", cr_y, "numeric"),
"term": cs.col("Term", cr_term, "categorical", levels=[terms[j] for j in cr_cols]), "label": cs.col("Row", cr_label, "categorical"),
}))
charts.append(cs.chart("influence-index", "influence-index", "Cook's distance by row", {
"cooks": cs.col("Cook's distance", np.asarray(cooks)[chart_rows], "numeric"), "index": cs.col("Row", (chart_rows + 1).tolist(), "numeric"),
}))
cs.publish({
"method": "regression.linear",
"methodVersion": "2.0.1",
"title": "Linear regression (OLS)",
"engine": cs.engine_info("pandas", "numpy", "statsmodels", "scipy"),
"n": n,
"summary": summary,
"apa": f"R² = {cs.fmt_num(r2, leading_zero=False)}, adjusted R² = {cs.fmt_num(adj_r2, leading_zero=False)}, F({df1:.0f}, {df2:.0f}) = {cs.fmt_num(f)}, {cs.fmt_p(f_p)}",
"statistics": [
{"key": "r_squared", "label": "R²", "value": r2}, {"key": "adj_r_squared", "label": "Adjusted R²", "value": adj_r2},
{"key": "f", "label": "F", "value": f}, {"key": "f_p", "label": "p (F test)", "value": f_p, "format": "p"},
{"key": "sigma", "label": "Residual SE", "value": sigma}, {"key": "aic", "label": "AIC", "value": aic},
],
"tables": tables,
"effectSizes": [{"key": "f2", "label": "Cohen's f²", "value": f2, "method": "R² / (1 − R²)"},
{"key": "r_squared", "label": "R²", "value": r2, "method": "1 − SSres / SStot"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Ordinary least squares; categorical predictors use treatment contrasts with the first stored level as reference; {se_label} standard errors."
+ (" With interactions, main effects are conditional on the other predictor being 0 (or at its reference level)." if interactions != "none" else "")],
"charts": charts,
"values": values,
})
This model uses lag 4, which you can set with Newey–West lag. Leave it empty for an automatic choice based on .
Rows must be in time order, so use Order by.
What robust errors don't fix
ReadIf robust and classical errors differ a lot, treat that as a signal to look for what's wrong with the model, not as the end of the investigation.
Check your understanding
CheckpointCheck yourself
You switch from classical to HC3 standard errors. What changes?
Show the answer
Answer: a
The coefficients and fit come from the same least-squares solution. Only the variance estimate changes.
Check yourself
You survey 2,000 customers in 150 stores about satisfaction, with store-level predictors. Which standard errors fit?
Show the answer
Answer: c
Customers in one store share conditions, so their errors correlate. With 150 clusters, cluster-robust errors are reliable.
Check yourself
Why are cluster-robust errors unreliable with 6 clusters and 10,000 rows?
Show the answer
Answer: b
Each cluster contributes a single piece of information about between-cluster variation. With few clusters, consider a wild cluster bootstrap or a mixed model.
Check yourself
Can HC3 errors fix a model missing an important confounder?
Show the answer
Answer: b
Robust to changing variance doesn't mean robust to omitted variables.
Choose yours
In the appSet Standard errors on the regression dialog. Cluster-robust needs a Cluster column; Newey–West uses Order by.
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("mtcars.csv")
model = smf.ols("mpg ~ hp + wt", data=df)
print(model.fit(cov_type="HC3").bse)
print(model.fit(cov_type="cluster", cov_kwds={"groups": df["cyl"]}).bse)
print(model.fit(cov_type="HAC", cov_kwds={"maxlags": 2}).bse)# install.packages(c("sandwich", "lmtest"))
library(sandwich); library(lmtest)
df <- read.csv("mtcars.csv")
fit <- lm(mpg ~ hp + wt, data = df)
coeftest(fit, vcov = vcovHC(fit, type = "HC3"))
coeftest(fit, vcov = vcovCL(fit, cluster = df$cyl))
coeftest(fit, vcov = NeweyWest(fit, lag = 2, prewhite = FALSE))Recap
Recap- A sandwich estimator keeps the coefficients and changes their uncertainty.
- Use HC3 for changing spread, cluster-robust for groups, Newey–West for time order.
- Cluster-robust needs many clusters, not many rows.
- Choose before seeing results. Robust errors don't fix bias.
Concepts in this lesson