Skip to content

Interactions: when one effect depends on another

Weight may cost automatic and manual cars different amounts of mileage. Interactions model that, and change what every other coefficient means.

Applied ~12 min11 steps

What runs in CodeSplash

You will be able to

  • Explain an interaction as a difference in slopes
  • Read main-effect coefficients correctly once an interaction is present
  • Use simple slopes and the Johnson–Neyman interval
  • Plan for the large samples that interactions need

Read first

01

A slope that depends on the group

Read

So far, each predictor has one slope. But maybe an extra thousand pounds costs a manual car more mileage than an automatic one. An interactionInteractionWhen the effect of one predictor depends on the level of another. lets the slope of one predictor depend on another:

y=β0+β1x+β2g+β3(x×g)+εy = \beta_0 + \beta_1 x + \beta_2 g + \beta_3 (x \times g) + \varepsilon

With gg coded 0/1, the slope of xx is β1\beta_1 when g=0g = 0 and β1+β3\beta_1 + \beta_3 when g=1g = 1. So β3\beta_3 is the difference between the slopes.

02

Play with it

Explore

DExplorable · Interactions and simple slopes

When the effect of x depends on a moderator, where is it actually different from zero?

What is the slope of x at this moderator value?

0.0
How sure?
0.50
120
0.0

Centering: with a mean far from zero, the coefficient on x describes a moderator value no one has.

1.0
no effectJ–NJ–N

Where the band excludes zero, the slope of x is significant at that moderator value. Johnson–Neyman (J–N) marks the boundaries.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Set the interaction to zero: the lines run parallel. Increase it: they fan out or cross. Note how the "main effect" of gg changes depending on where you measure the gap between the lines.

03

Main effects change meaning

Read

Here's the trap. With an interaction in the model, β1\beta_1 is the slope of xx only when g=0g = 0, and β2\beta_2 is the group difference only when x=0x = 0.

If x=0x = 0 is meaningless, like zero weight for a car, then β2\beta_2 measures a gap that doesn't exist anywhere in your data. Center numeric predictors on their mean before fitting: β2\beta_2 then becomes the group difference at the typical value of xx.

04

Predict the pattern

Predict

Predict first

Mileage against weight, split by transmission. Manual cars in mtcars are mostly light and vary widely in weight and mileage. Which group has the steeper negative slope?

Slopes are about equalManual cars have the steeper slopeAutomatic cars have the steeper slope
Reveal

Manual cars lose mileage much faster per thousand pounds. The card's simple slopes table below shows each group's slope, with its own interval. The model reaches R2R^2 = 0.833.

05

Read the card

In the app
Linear regression (OLS)Recorded · Python and R agreeRecorded 2026-11-17 · 72 values compared
R

R² = .83, adjusted R² = .82, F(3, 28) = 46.57, p < .001

R²
0.8330
Adjusted R²
0.8151
F
46.567
p (F test)
< .001
Residual SE
2.591
AIC
157.48

Effect size

  • Cohen's f² 4.989
  • R² 0.8330

Plots

Residual diagnosticsDo a model's residuals show non-linearity, non-normality, unequal spread or influential points?
View data
Cook's distanceFittedLeverageResidualStandardized residual
0.008622.4940.0865−1.494−0.6031
0.004120.1770.12410.82280.3393
0.020225.2190.0787−2.419−0.9726
0.016619.2440.08082.1560.8677
0.000318.3930.06260.30750.1226
0.000118.3170.0614−0.2168−0.0864
0.030517.9000.0563−3.600−1.430
0.094719.3390.08345.0612.040
0.043119.4900.08783.3101.337
0.001718.3930.06260.80750.3218
0.000918.3930.0626−0.5925−0.2362
0.000416.0070.06100.39260.1563
6.338e-817.2950.05280.00540.0021
0.007917.1050.0526−1.905−0.7554
0.022111.5400.2543−1.140−0.5095
0.005410.8810.3045−0.4813−0.2227
0.250711.1800.28103.5201.602
0.143526.3090.08676.0912.460
0.019531.6230.2156−1.223−0.5331
0.140729.6250.14964.2751.789
0.004222.0840.2089−0.5838−0.2533
0.016418.0900.0583−2.590−1.030
0.027518.4110.0629−3.211−1.280
0.028216.8780.0531−3.578−1.419
0.012116.8590.05322.3410.9283
0.012428.7160.1265−1.416−0.5849
0.003126.8540.0930−0.8541−0.3461
0.078332.5500.2535−2.150−0.9603
0.034317.4970.2030−1.697−0.7337
0.010021.1310.1051−1.431−0.5838
0.045113.8640.37101.1360.5529
0.000621.0400.10670.35980.1469
Estimated marginal means of mpg by am_fWhat does the model predict for each group (and does the effect of one factor depend on another)?
View data
highlowmpg (EMM)am_f
20.74317.72919.236automatic
19.55314.58317.068manual
Added-variable plotsWhat does one predictor add once the others are accounted for, and which rows drive it?
View data
RowTermPredictor given the othersmpg given the others
row 1weight (1000 lbs)−3.092e-15−1.494
row 2weight (1000 lbs)1.241e-150.8228
row 3weight (1000 lbs)7.156e-16−2.419
row 4weight (1000 lbs)−0.55394.253
row 5weight (1000 lbs)−0.32891.553
row 6weight (1000 lbs)−0.30890.9526
row 7weight (1000 lbs)−0.1989−2.847
row 8weight (1000 lbs)−0.57897.253
row 9weight (1000 lbs)−0.61895.653
row 10weight (1000 lbs)−0.32892.053
row 11weight (1000 lbs)−0.32890.6526
row 12weight (1000 lbs)0.3011−0.7474
row 13weight (1000 lbs)−0.03890.1526
row 14weight (1000 lbs)0.0111−1.947
row 15weight (1000 lbs)1.481−6.747
row 16weight (1000 lbs)1.655−6.747
row 17weight (1000 lbs)1.576−2.447
row 18weight (1000 lbs)3.822e-176.091
row 19weight (1000 lbs)−1.839e-17−1.223
row 20weight (1000 lbs)4.259e-174.275
row 21weight (1000 lbs)−1.3044.353
row 22weight (1000 lbs)−0.2489−1.647
row 23weight (1000 lbs)−0.3339−1.947
row 24weight (1000 lbs)0.0711−3.847
row 25weight (1000 lbs)0.07612.053
row 26weight (1000 lbs)−1.212e-17−1.416
row 27weight (1000 lbs)4.732e-17−0.8541
row 28weight (1000 lbs)−2.920e-18−2.150
row 29weight (1000 lbs)−1.670e-17−1.697
row 30weight (1000 lbs)8.268e-17−1.431
row 31weight (1000 lbs)3.985e-171.136
row 32weight (1000 lbs)8.652e-170.3598
row 1am_f: manual−0.0123−1.677
row 2am_f: manual−0.0620−0.1002
row 3am_f: manual0.0461−1.732
row 4am_f: manual−0.09030.8120
row 5am_f: manual−0.0615−0.6078
row 6am_f: manual−0.0590−1.094
row 7am_f: manual−0.0449−4.268
row 8am_f: manual−0.09353.670
row 9am_f: manual−0.09861.842
row 10am_f: manual−0.0615−0.1078
row 11am_f: manual−0.0615−1.508
row 12am_f: manual0.01910.6766
row 13am_f: manual−0.0244−0.3578
row 14am_f: manual−0.0180−2.173
row 15am_f: manual0.17011.390
row 16am_f: manual0.19232.380
row 17am_f: manual0.18226.231
row 18am_f: manual0.06957.125
row 19am_f: manual0.18361.508
row 20am_f: manual0.14076.368
row 21am_f: manual−0.1863−3.355
row 22am_f: manual−0.0513−3.353
row 23am_f: manual−0.0622−4.136
row 24am_f: manual−0.0103−3.732
row 25am_f: manual−0.00972.196
row 26am_f: manual0.12120.3867
row 27am_f: manual0.08120.3544
row 28am_f: manual0.20340.8769

First 60 of 96 rows.

Cook's distance by rowWhich rows pull the fit the most?
View data
Cook's distanceRow
0.00861
0.00412
0.02023
0.01664
0.00035
0.00016
0.03057
0.09478
0.04319
0.001710
0.000911
0.000412
6.338e-813
0.007914
0.022115
0.005416
0.250717
0.143518
0.019519
0.140720
0.004221
0.016422
0.027523
0.028224
0.012125
0.012426
0.003127
0.078328
0.034329
0.010030
0.045131
0.000632

Assumptions

  • Normality of residuals — Shapiro–Wilk W = 0.942, p = .087.
  • Constant variance — Breusch–Pagan (Koenker) χ²(3) = 1.45, p = .694.
  • Multicollinearity — Largest VIF 1.92 (am_f); interaction columns are left out (their correlation with main effects is structural).
  • Linearity — RESET F(2, 26) = 1.50, p = .243.
  • Independent residuals — Durbin–Watson = 1.79 (≈ 2 when residuals in row order are uncorrelated; only meaningful for ordered rows).
  • Influential points — 3 row(s) with Cook's distance above 4/n = 0.125; largest 0.251.

Coefficients

TermEstimateSEtp95% CI low95% CI highβ (std.)
(Intercept)31.4163.02010.402< .00125.23037.602—
weight (1000 lbs)−3.7860.7856−4.819< .001−5.395−2.177−0.6146
am_f: manual14.8784.2643.489.0026.14423.6131.232
weight (1000 lbs) × am_f: manual−5.2981.445−3.667.001−8.258−2.339−1.110

Standard errors: classical; t tests with 28 df.

Simple slopes of weight (1000 lbs)

AtSlopeSEtp95% CI low95% CI high
am_f = automatic−3.7860.7856−4.819< .001−5.395−2.177
am_f = manual−9.0841.212−7.493< .001−11.568−6.601

Estimated marginal means

FactorLevelEMMSE95% CI low95% CI high
am_fautomatic19.2360.735717.72920.743
am_fmanual17.0681.21314.58319.553

Other factors averaged with equal weights; numeric predictors at their means.

Pairwise comparisons of marginal means

FactorContrastDifferenceSEtp (adj.)CI lowCI high
am_fautomatic - manual2.1681.4191.528.138−0.73875.074

Adjustment: holm (within each factor).

Most influential rows (Cook's distance)

RowFittedResidualStudentizedLeverageCook's D
1711.1803.5201.6500.28100.2507
1826.3096.0912.7280.08670.1435
2029.6254.2751.8670.14960.1407
819.3395.0612.1710.08340.0947
2832.550−2.150−0.95890.25350.0783
3113.8641.1360.54600.37100.0451
919.4903.3101.3570.08780.0431
2917.497−1.697−0.72750.20300.0343
717.900−3.600−1.4590.05630.0305
2416.878−3.578−1.4460.05310.0282

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; classical standard errors. With interactions, main effects are conditional on the other predictor being 0 (or at its reference level).
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 38fd5aacd1896790
# Dataset: mtcars (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/mtcars.parquet", col_select = c("mpg", "weight (1000 lbs)", "am_f")))
n_input <- nrow(df)
df[["am_f"]] <- factor(df[["am_f"]], levels = c("automatic", "manual"))  # stored level order
df <- df[stats::complete.cases(df[c("mpg", "weight (1000 lbs)", "am_f")]), , 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("mpg", "weight (1000 lbs)", "am_f"))  # infinite values stop the run (registry/errors.yaml)

# %% Fit
y <- "mpg"
predictors <- c("weight (1000 lbs)", "am_f")
conf <- 0.95
interactions <- "first-two"  # none | first-two | all-pairs
se_type <- "classical"  # classical | HC0-HC3 | cluster | HAC
diagnostics <- "standard"  # 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_col <- NULL
ord_idx <- seq_len(n)
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(3)
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(1)
  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 <- "holm"
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
))
Python

R² = .83, adjusted R² = .82, F(3, 28) = 46.57, p < .001

R²
0.8330
Adjusted R²
0.8151
F
46.567
p (F test)
< .001
Residual SE
2.591
AIC
157.48

Effect size

  • Cohen's f² 4.989
  • R² 0.8330

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

Assumptions

  • Normality of residuals — Shapiro–Wilk W = 0.942, p = .087.
  • Constant variance — Breusch–Pagan (Koenker) χ²(3) = 1.45, p = .694.
  • Multicollinearity — Largest VIF 1.92 (am_f); interaction columns are left out (their correlation with main effects is structural).
  • Linearity — RESET F(2, 26) = 1.50, p = .243.
  • Independent residuals — Durbin–Watson = 1.79 (≈ 2 when residuals in row order are uncorrelated; only meaningful for ordered rows).
  • Influential points — 3 row(s) with Cook's distance above 4/n = 0.125; largest 0.251.

Coefficients

TermEstimateSEtp95% CI low95% CI highβ (std.)
(Intercept)31.4163.02010.402< .00125.23037.602—
weight (1000 lbs)−3.7860.7856−4.819< .001−5.395−2.177−0.6146
am_f: manual14.8784.2643.489.0026.14423.6131.232
weight (1000 lbs) × am_f: manual−5.2981.445−3.667.001−8.258−2.339−1.110

Standard errors: classical; t tests with 28 df.

Simple slopes of weight (1000 lbs)

AtSlopeSEtp95% CI low95% CI high
am_f = automatic−3.7860.7856−4.819< .001−5.395−2.177
am_f = manual−9.0841.212−7.493< .001−11.568−6.601

Estimated marginal means

FactorLevelEMMSE95% CI low95% CI high
am_fautomatic19.2360.735717.72920.743
am_fmanual17.0681.21314.58319.553

Other factors averaged with equal weights; numeric predictors at their means.

Pairwise comparisons of marginal means

FactorContrastDifferenceSEtp (adj.)CI lowCI high
am_fautomatic - manual2.1681.4191.528.138−0.73875.074

Adjustment: holm (within each factor).

Most influential rows (Cook's distance)

RowFittedResidualStudentizedLeverageCook's D
1711.1803.5201.6500.28100.2507
1826.3096.0912.7280.08670.1435
2029.6254.2751.8670.14960.1407
819.3395.0612.1710.08340.0947
2832.550−2.150−0.95890.25350.0783
3113.8641.1360.54600.37100.0451
919.4903.3101.3570.08780.0431
2917.497−1.697−0.72750.20300.0343
717.900−3.600−1.4590.05630.0305
2416.878−3.578−1.4460.05310.0282

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; classical standard errors. With interactions, main effects are conditional on the other predictor being 0 (or at its reference level).
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 38fd5aacd1896790
# Dataset: mtcars (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/mtcars.parquet", columns=["mpg", "weight (1000 lbs)", "am_f"])
n_input = len(df)
df["am_f"] = pd.Categorical(df["am_f"], categories=["automatic", "manual"])  # stored level order
df = df.dropna(subset=["mpg", "weight (1000 lbs)", "am_f"])  # listwise deletion over the analysis columns
df["am_f"] = df["am_f"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["mpg", "weight (1000 lbs)", "am_f"])  # infinite values stop the run (registry/errors.yaml)

# %% Design matrix
y = "mpg"
predictors = ["weight (1000 lbs)", "am_f"]
conf = 0.95
interactions = "first-two"  # none | first-two | all-pairs
se_type = "classical"  # classical | HC0–HC3 | cluster | HAC
diagnostics = "standard"  # 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_col = None
ord_idx = np.arange(n)

# %% 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(3)
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(1)
    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 = "holm"
    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,
})

Look for the interaction row (weight × transmission) first. If you believe the interaction, read the simple slopes rather than the main-effect rows.

Be careful about extrapolation: heavy manual cars and light automatics hardly exist in this sample, so the lines are compared across a range where few cars overlap.

06

Two numeric predictors

Read

With two numeric predictors, there aren't two lines but a whole family. The Johnson–NeymanJohnson–Neyman intervalThe range of a moderator over which the focal predictor's slope is statistically distinguishable from zero. interval tells you where the slope of one predictor is distinguishable from zero.

In airquality, with ozone modeled on a temperature × wind interaction, the boundaries for wind speed fall at 15.4 and 24.4. Temperature's slope is distinguishable from zero outside that range.

07

Interactions need many rows

Read

A difference between slopes is harder to estimate than a slope. With balanced groups, detecting an interaction as large as a main effect takes about four times the sample; realistic smaller interactions take far more.

So a non-significant interaction doesn't show the slopes are equal, and a significant one in a small sample often overstates its size. Decide which interactions you care about before looking.

08

Moderator or mediator?

Predict

An interaction is moderation: the effect of xx depends on zz. A mediatorMediatorA variable on the path from treatment to outcome; adjusting for it removes part of the effect you want. answers a different question: how much of the effect of xx travels through mm?

Predict first

A training course raises motivation, and motivation raises test scores. What is motivation here?

A moderatorA mediatorA confounder
Reveal

A mediator. In these simulated data, the indirect effect is 1.40 and the direct effect is 1.61, so about 47% of the total is mediated. A causal reading assumes nothing unmeasured links motivation and scores, and randomizing the course doesn't guarantee that.

Mediation analysisRecorded · Python and R agreeRecorded 2026-11-17 · 51 values compared
R

ACME = 1.40, 95% CI [1.01, 1.82], p < .001

ACME (indirect)
1.404
p
< .001
ADE (direct)
1.609
Total
3.014
Proportion mediated
0.4659

Plots

Indirect, direct and total effectsHow large are several estimates, how precise, and which exclude the null?
View data
EstimatehighEffectlow
1.4041.824ACME (average)1.007
1.6091.959ADE (average)1.204
3.0143.481Total effect2.479

Assumptions

  • Sequential ignorability — Not testable: the effects are causal only if no unmeasured variable confounds exposure–mediator, exposure–outcome or mediator–outcome beyond the 2 covariates adjusted for.
  • Exposure × mediator interaction — In a model with the interaction its coefficient is 0.350 (p = .051); leaving it out is reasonable.
  • Exposure → mediator → outcome in time — motivation should be measured after treat and before score; otherwise the indirect effect has no causal meaning.

Effects of treat (true vs false)

EffectEstimate95% CI low95% CI highp
ACME (average)1.4041.0071.824< .001
ADE (average)1.6091.2041.959< .001
Total effect3.0142.4793.481< .001
Proportion mediated0.46590.37070.5730< .001

ACME: the change in the outcome when only the mediator moves as the exposure would move it; ADE: the change with the mediator held fixed.

Model paths

PathBSEtp
a: treat → motivation0.90040.12217.375< .001
b: motivation → score (given treat)1.5590.091916.964< .001
c′: treat → score (direct)1.6090.20987.672< .001
  • Linear mediator and outcome models (OLS); covariates at their sample means. Intervals: nonparametric bootstrap (500 of 500 resamples, percentile intervals). Seed 42: the same draws in Python and R.
The exact R script · R R version 4.5.1 (2025-06-13)
# Mediation analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.mediation 1.0.1 · spec c31703dd14cd7fc1
# Dataset: c3_mediation (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c3_mediation.parquet", col_select = c("score", "treat", "motivation", "age", "region")))
n_input <- nrow(df)
df[["treat"]] <- factor(df[["treat"]], levels = c("false", "true"))  # stored level order
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "West"))  # stored level order
df <- df[stats::complete.cases(df[c("score", "treat", "motivation", "age", "region")]), , 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("score", "treat", "motivation", "age", "region"))  # infinite values stop the run (registry/errors.yaml)

# %% Variables
outcome <- "score"
exposure <- "treat"
mediator <- "motivation"
covariates <- c("age", "region")
interaction <- FALSE  # exposure x mediator term in the outcome model
ci_method <- "bootstrap"  # bootstrap | quasi_bayes | delta
sims <- as.integer(500)
seed <- 42  # portable Wichmann-Hill stream: Python draws the same resamples for this seed
conf <- 0.95
control_value <- NULL
treat_value <- NULL
if (ci_method == "delta" && interaction) stop("The delta method covers the product a·b only; use the bootstrap or quasi-Bayesian intervals with the interaction.")
ex <- df[[exposure]]
if (is.factor(ex)) {
  levels_ex <- levels(ex)
  if (length(levels_ex) != 2) cs_error("CS_E_GROUP_COUNT", column = exposure, expected = 2, k = length(levels_ex))
  x <- as.numeric(as.character(ex) == levels_ex[2])
  x0 <- 0
  x1 <- 1
  contrast <- sprintf("%s vs %s", levels_ex[2], levels_ex[1])
} else if (is.logical(ex)) {
  x <- as.numeric(ex)
  x0 <- 0
  x1 <- 1
  contrast <- "true vs false"
} else {
  x <- as.numeric(ex)
  x0 <- if (is.null(control_value)) 0 else control_value
  x1 <- if (is.null(treat_value)) 1 else treat_value
  if (x0 == x1) stop("The control and treatment values of the exposure must differ.")
  contrast <- sprintf("%s vs %s", sprintf("%g", x1), sprintf("%g", x0))
}
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
# More rows than coefficients of the largest model: the outcome model with the exposure x mediator
# term (always fitted, to check the interaction) has 4 coefficients plus the covariate columns.
k_cov <- length(cs_design_labels(df, covariates)) - 1
cs_check_rows(nrow(df), 4 + k_cov + 1, "Mediation analysis")
for (col in c(outcome, exposure, mediator, covariates)) cs_check_not_constant(df[[col]], col)  # one value (or one level with data) is no variation
m <- as.numeric(df[[mediator]])
y <- as.numeric(df[[outcome]])
C <- if (length(covariates)) unname(model.matrix(cs_model_formula(outcome, covariates, "none"), data = df)[, -1, drop = FALSE]) else matrix(0, nrow(df), 0)
n <- nrow(df)
cbar <- if (ncol(C)) colMeans(C) else numeric(0)

# %% Fit the mediator and outcome models
fits <- cs_med_fit(x, m, y, C, interaction)
fm <- fits$m
fy <- fits$y
fy_int <- cs_med_fit(x, m, y, C, TRUE)$y  # with the interaction, to check it
path <- function(fit, j) {
  est <- fit$coef[j]
  se <- sqrt(fit$cov[j, j])
  c(est = est, se = se, t = est / se, p = 2 * pt(abs(est / se), fit$df, lower.tail = FALSE))
}
pa <- path(fm, 2)
pb <- path(fy, 3)
pc <- path(fy, 2)
pxm <- path(fy_int, 4)
a <- unname(pa["est"]); a_se <- unname(pa["se"]); a_p <- unname(pa["p"])
b <- unname(pb["est"]); b_se <- unname(pb["se"]); b_p <- unname(pb["p"])
c_prime <- unname(pc["est"]); c_se <- unname(pc["se"]); c_p <- unname(pc["p"])
xm <- unname(pxm["est"]); xm_se <- unname(pxm["se"]); xm_p <- unname(pxm["p"])
keys <- c("acme_control", "acme_treated", "ade_control", "ade_treated", "acme", "ade", "total", "prop_mediated")
point <- setNames(as.list(cs_med_effects(fm$coef, fy$coef, x0, x1, cbar, interaction)), keys)

# %% Intervals
n_failed <- 0L
n_used <- NULL
if (ci_method == "delta") {
  delta <- x1 - x0
  sig <- matrix(0, 3, 3)  # theta = (a, c', b)
  sig[1, 1] <- fm$cov[2, 2]
  sig[2:3, 2:3] <- fy$cov[2:3, 2:3]
  tot <- c_prime + a * b
  grads <- list(acme = delta * c(b, 0, a), ade = delta * c(0, 1, 0), total = delta * c(b, 1, a),
                prop_mediated = c(b * c_prime, -a * b, a * c_prime) / tot^2)
  zc <- qnorm(1 - (1 - conf) / 2)
  summ <- list()
  for (key in names(grads)) {
    g <- grads[[key]]
    se_k <- sqrt(drop(t(g) %*% sig %*% g))
    est <- point[[key]]
    summ[[key]] <- list(ci_low = est - zc * se_k, ci_high = est + zc * se_k, p = 2 * pnorm(abs(est / se_k), lower.tail = FALSE))
  }
  summ$acme_control <- summ$acme
  summ$acme_treated <- summ$acme
  summ$ade_control <- summ$ade
  summ$ade_treated <- summ$ade
} else {
  if (ci_method == "bootstrap") {
    bs <- cs_med_bootstrap(x, m, y, C, interaction, x0, x1, sims, seed)
    draws <- bs$draws
    n_failed <- bs$failed
  } else {
    draws <- cs_med_quasi_bayes(fm, fy, interaction, x0, x1, cbar, sims, seed)
  }
  summ <- cs_med_summarize(draws, conf)
  n_used <- nrow(draws)
}
sobel_z <- if (interaction) NULL else a * b / sqrt(b^2 * a_se^2 + a^2 * b_se^2)
sobel_p <- if (interaction) NULL else 2 * pnorm(abs(sobel_z), lower.tail = FALSE)

# %% Assumptions
assumptions <- list(
  list(key = "ignorability", label = "Sequential ignorability", status = "info",
       detail = paste0("Not testable: the effects are causal only if no unmeasured variable confounds exposure–mediator, exposure–outcome or mediator–outcome",
                       if (length(covariates)) sprintf(" beyond the %d covariates adjusted for.", length(covariates)) else "; no covariates are adjusted for.")),
  if (!interaction) {
    list(key = "interaction", label = "Exposure × mediator interaction", status = if (xm_p < 1 - conf) "warn" else "pass", p = xm_p,
         detail = paste0(sprintf("In a model with the interaction its coefficient is %.3f (%s)", xm, cs_fmt_p(xm_p)),
                         if (xm_p < 1 - conf) "; the mediator's effect differs by exposure — include the interaction." else "; leaving it out is reasonable."))
  } else {
    list(key = "interaction", label = "Exposure × mediator interaction", status = "info", p = xm_p,
         detail = sprintf("Included: coefficient %.3f (%s); effects are reported with the exposure held at control and at treatment.", xm, cs_fmt_p(xm_p)))
  },
  list(key = "ordering", label = "Exposure → mediator → outcome in time", status = "info",
       detail = sprintf("%s should be measured after %s and before %s; otherwise the indirect effect has no causal meaning.", mediator, exposure, outcome))
)

# %% Result
labels <- c(acme_control = "ACME (control)", acme_treated = "ACME (treated)", ade_control = "ADE (control)", ade_treated = "ADE (treated)",
            acme = "ACME (average)", ade = "ADE (average)", total = "Total effect", prop_mediated = "Proportion mediated")
order <- if (interaction) keys else c("acme", "ade", "total", "prop_mediated")
fin <- function(v) if (is.null(v) || !is.finite(v)) NULL else v
effect_rows <- lapply(order, function(k) list(effect = labels[[k]], estimate = fin(point[[k]]), ci_low = fin(summ[[k]]$ci_low), ci_high = fin(summ[[k]]$ci_high), p = fin(summ[[k]]$p)))
values <- list(n = n, x0 = x0, x1 = x1, interaction = interaction, ci_method = ci_method, sims = if (ci_method != "delta") sims else NULL,
               n_used = n_used, n_failed = n_failed, a = a, a_se = a_se, a_p = a_p, b = b, b_se = b_se, b_p = b_p,
               c_prime = c_prime, c_prime_se = c_se, c_prime_p = c_p, xm = xm, xm_se = xm_se, xm_p = xm_p, sobel_z = sobel_z, sobel_p = sobel_p,
               missing_share = if (n_input > 0) n_dropped / n_input else 0)
for (k in keys) {
  values[k] <- list(fin(point[[k]]))  # `[<-` with list(NULL) keeps a null value (Python's None)
  values[paste0(k, "_ci_low")] <- list(fin(summ[[k]]$ci_low))
  values[paste0(k, "_ci_high")] <- list(fin(summ[[k]]$ci_high))
  if (k %in% c("acme", "ade", "total", "prop_mediated")) values[paste0(k, "_p")] <- list(fin(summ[[k]]$p))
}
paths <- list(
  list(path = sprintf("a: %s → %s", exposure, mediator), estimate = a, se = a_se, t = unname(pa["t"]), p = a_p),
  list(path = sprintf("b: %s → %s (given %s)", mediator, outcome, exposure), estimate = b, se = b_se, t = unname(pb["t"]), p = b_p),
  list(path = sprintf("c′: %s → %s (direct)", exposure, outcome), estimate = c_prime, se = c_se, t = unname(pc["t"]), p = c_p)
)
if (interaction) paths[[4]] <- list(path = sprintf("%s × %s", exposure, mediator), estimate = xm, se = xm_se, t = unname(pxm["t"]), p = xm_p)
method_name <- c(bootstrap = sprintf("nonparametric bootstrap (%s of %d resamples, percentile intervals)", format(n_used), sims),
                 quasi_bayes = sprintf("quasi-Bayesian simulation (%d draws, percentile intervals)", sims),
                 delta = "delta method (normal approximation)")[[ci_method]]
pct <- sprintf("%.0f%%", conf * 100)
pm <- point$prop_mediated
summary <- paste0(sprintf("Effect of %s (%s) on %s through %s (n = %d): ACME = %.3f [%.3f, %.3f], %s; ADE = %.3f; total = %.3f",
                          exposure, contrast, outcome, mediator, n, point$acme, summ$acme$ci_low, summ$acme$ci_high, cs_fmt_p(summ$acme$p), point$ade, point$total),
                  if (is.finite(pm)) sprintf("; proportion mediated %.2f.", pm) else ".")
chart_rows <- Filter(function(r) r$effect != "Proportion mediated", effect_rows)
cs_publish(list(
  method = "regression.mediation",
  methodVersion = "1.0.1",
  title = "Mediation analysis",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("ACME = %.2f, %s CI [%.2f, %.2f], %s", point$acme, pct, summ$acme$ci_low, summ$acme$ci_high, cs_fmt_p(summ$acme$p)),
  statistics = list(list(key = "acme", label = "ACME (indirect)", value = fin(point$acme)), list(key = "acme_p", label = "p", value = fin(summ$acme$p), format = "p"),
                    list(key = "ade", label = "ADE (direct)", value = fin(point$ade)), list(key = "total", label = "Total", value = fin(point$total)),
                    list(key = "prop_mediated", label = "Proportion mediated", value = fin(pm))),
  tables = list(
    list(key = "effects", title = sprintf("Effects of %s (%s)", exposure, contrast), columns = list(
      list(key = "effect", label = "Effect", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
      list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"),
      list(key = "p", label = "p", type = "pvalue")),
      rows = effect_rows, note = "ACME: the change in the outcome when only the mediator moves as the exposure would move it; ADE: the change with the mediator held fixed."),
    list(key = "paths", title = "Model paths", columns = list(
      list(key = "path", label = "Path", type = "string"), list(key = "estimate", label = "B", type = "number"),
      list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "pvalue")),
      rows = paths)
  ),
  effectSizes = list(),
  assumptions = assumptions,
  warnings = c(warnings, if (n_failed > 0) sprintf("%d resamples lost a variable's variation and were skipped.", n_failed)),
  notes = list(paste0(sprintf("Linear mediator and outcome models (OLS)%s; covariates at their sample means. Intervals: %s.",
                              if (interaction) ", outcome model with the exposure × mediator interaction" else "", method_name),
                      if (ci_method != "delta") sprintf(" Seed %s: the same draws in Python and R.", format(seed)) else "")),
  charts = list(cs_chart("effects", "forest", "Indirect, direct and total effects", list(
    label = cs_col("Effect", vapply(chart_rows, `[[`, "", "effect"), kind = "categorical"),
    estimate = cs_col("Estimate", vapply(chart_rows, function(r) if (is.null(r$estimate)) NA_real_ else r$estimate, 0)),
    low = cs_col("low", vapply(chart_rows, function(r) if (is.null(r$ci_low)) NA_real_ else r$ci_low, 0)),
    high = cs_col("high", vapply(chart_rows, function(r) if (is.null(r$ci_high)) NA_real_ else r$ci_high, 0))), controls = list(reference = 0))),
  values = values
))
Python

ACME = 1.40, 95% CI [1.01, 1.82], p < .001

ACME (indirect)
1.404
p
< .001
ADE (direct)
1.609
Total
3.014
Proportion mediated
0.4659

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

Assumptions

  • Sequential ignorability — Not testable: the effects are causal only if no unmeasured variable confounds exposure–mediator, exposure–outcome or mediator–outcome beyond the 2 covariates adjusted for.
  • Exposure × mediator interaction — In a model with the interaction its coefficient is 0.350 (p = .051); leaving it out is reasonable.
  • Exposure → mediator → outcome in time — motivation should be measured after treat and before score; otherwise the indirect effect has no causal meaning.

Effects of treat (true vs false)

EffectEstimate95% CI low95% CI highp
ACME (average)1.4041.0071.824< .001
ADE (average)1.6091.2041.959< .001
Total effect3.0142.4793.481< .001
Proportion mediated0.46590.37070.5730< .001

ACME: the change in the outcome when only the mediator moves as the exposure would move it; ADE: the change with the mediator held fixed.

Model paths

PathBSEtp
a: treat → motivation0.90040.12217.375< .001
b: motivation → score (given treat)1.5590.091916.964< .001
c′: treat → score (direct)1.6090.20987.672< .001
  • Linear mediator and outcome models (OLS); covariates at their sample means. Intervals: nonparametric bootstrap (500 of 500 resamples, percentile intervals). Seed 42: the same draws in Python and R.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Mediation analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.mediation 1.0.1 · spec c31703dd14cd7fc1
# Dataset: c3_mediation (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import mediation as csmed
from codesplash.stats import regression as csreg

# %% Data
df = pd.read_parquet("tests/parity/fixtures/c3_mediation.parquet", columns=["score", "treat", "motivation", "age", "region"])
n_input = len(df)
df["treat"] = pd.Categorical(df["treat"], categories=["false", "true"])  # stored level order
df["region"] = pd.Categorical(df["region"], categories=["North", "South", "West"])  # stored level order
df = df.dropna(subset=["score", "treat", "motivation", "age", "region"])  # listwise deletion over the analysis columns
df["treat"] = df["treat"].cat.remove_unused_categories()
df["region"] = df["region"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["score", "treat", "motivation", "age", "region"])  # infinite values stop the run (registry/errors.yaml)

# %% Variables
outcome = "score"
exposure = "treat"
mediator = "motivation"
covariates = ["age", "region"]
interaction = False  # exposure × mediator term in the outcome model
ci_method = "bootstrap"  # bootstrap | quasi_bayes | delta
sims = int(500)
seed = 42  # portable Wichmann–Hill stream: R draws the same resamples for this seed
conf = 0.95
control_value = None
treat_value = None
if ci_method == "delta" and interaction:
    raise ValueError("The delta method covers the product a·b only; use the bootstrap or quasi-Bayesian intervals with the interaction.")
ex = df[exposure]
if isinstance(ex.dtype, pd.CategoricalDtype):
    levels = [str(v) for v in ex.cat.categories]
    if len(levels) != 2:
        cs.cs_error("CS_E_GROUP_COUNT", column=exposure, expected=2, k=len(levels))
    x = (ex.astype(str) == levels[1]).to_numpy(dtype=float)
    x0, x1, contrast = 0.0, 1.0, f"{levels[1]} vs {levels[0]}"
elif ex.dtype == bool:
    x = ex.to_numpy(dtype=float)
    x0, x1, contrast = 0.0, 1.0, "true vs false"
else:
    x = ex.to_numpy(dtype=float)
    x0 = 0.0 if control_value is None else float(control_value)
    x1 = 1.0 if treat_value is None else float(treat_value)
    if x0 == x1:
        raise ValueError("The control and treatment values of the exposure must differ.")
    contrast = f"{x1:g} vs {x0:g}"
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
# More rows than coefficients of the largest model: the outcome model with the exposure × mediator
# term (always fitted, to check the interaction) has 4 coefficients plus the covariate columns.
k_cov = csreg.design_matrix(df, covariates, "none").shape[1] - 1
cs.check_rows(len(df), 4 + k_cov + 1, "Mediation analysis")
for col in [outcome, exposure, mediator] + covariates:
    check_not_constant(df[col], col)  # one value (or one level with data) is no variation
m = df[mediator].to_numpy(dtype=float)
y = df[outcome].to_numpy(dtype=float)
if covariates:
    C = csreg.design_matrix(df, covariates, "none").drop(columns="(Intercept)").to_numpy(dtype=float)
else:
    C = np.zeros((len(df), 0))
n = len(df)
cbar = C.mean(axis=0) if C.shape[1] else np.zeros(0)

# %% Fit the mediator and outcome models
fm, fy = csmed.fit(x, m, y, C, interaction)
_, fy_int = csmed.fit(x, m, y, C, True)  # with the interaction, to check it


def path(fit, j):
    est, se = float(fit["coef"][j]), float(np.sqrt(fit["cov"][j, j]))
    return est, se, est / se, float(2 * stats.t.sf(abs(est / se), fit["df"]))


a, a_se, a_t, a_p = path(fm, 1)
b, b_se, b_t, b_p = path(fy, 2)
c_prime, c_se, c_t, c_p = path(fy, 1)
xm, xm_se, xm_t, xm_p = path(fy_int, 3)
point = csmed.effects(fm["coef"], fy["coef"], x0, x1, cbar, interaction)

# %% Intervals
n_failed = 0
if ci_method == "delta":
    delta = x1 - x0
    va = fm["cov"][1, 1]
    cy = fy["cov"][np.ix_([1, 2], [1, 2])]  # (c', b)
    sig = np.array([[va, 0, 0], [0, cy[0, 0], cy[0, 1]], [0, cy[1, 0], cy[1, 1]]])  # θ = (a, c', b)
    tot = c_prime + a * b
    grads = {"acme": delta * np.array([b, 0, a]), "ade": delta * np.array([0, 1, 0]), "total": delta * np.array([b, 1, a]),
             "prop_mediated": np.array([b * c_prime, -a * b, a * c_prime]) / tot**2}
    zc = stats.norm.ppf(1 - (1 - conf) / 2)
    summ = {}
    for key, g in grads.items():
        se_k = float(np.sqrt(g @ sig @ g))
        est = point[key]
        summ[key] = {"ci_low": est - zc * se_k, "ci_high": est + zc * se_k, "p": float(2 * stats.norm.sf(abs(est / se_k)))}
    for key, src in (("acme_control", "acme"), ("acme_treated", "acme"), ("ade_control", "ade"), ("ade_treated", "ade")):
        summ[key] = summ[src]
    n_used = None
else:
    if ci_method == "bootstrap":
        draws, n_failed = csmed.bootstrap(x, m, y, C, interaction, x0, x1, sims, seed)
    else:
        draws = csmed.quasi_bayes(fm, fy, interaction, x0, x1, cbar, sims, seed)
    summ = csmed.summarize(draws, conf)
    n_used = int(draws.shape[0])
sobel_z = None if interaction else float(a * b / np.sqrt(b**2 * a_se**2 + a**2 * b_se**2))
sobel_p = None if interaction else float(2 * stats.norm.sf(abs(sobel_z)))

# %% Assumptions
assumptions = [
    {"key": "ignorability", "label": "Sequential ignorability", "status": "info",
     "detail": "Not testable: the effects are causal only if no unmeasured variable confounds exposure–mediator, exposure–outcome or mediator–outcome"
               + (f" beyond the {len(covariates)} covariates adjusted for." if covariates else "; no covariates are adjusted for.")},
    ({"key": "interaction", "label": "Exposure × mediator interaction", "status": "warn" if xm_p < 1 - conf else "pass", "p": xm_p,
      "detail": f"In a model with the interaction its coefficient is {xm:.3f} ({cs.fmt_p(xm_p)})"
                + ("; the mediator's effect differs by exposure — include the interaction." if xm_p < 1 - conf else "; leaving it out is reasonable.")}
     if not interaction else
     {"key": "interaction", "label": "Exposure × mediator interaction", "status": "info", "p": xm_p,
      "detail": f"Included: coefficient {xm:.3f} ({cs.fmt_p(xm_p)}); effects are reported with the exposure held at control and at treatment."}),
    {"key": "ordering", "label": "Exposure → mediator → outcome in time", "status": "info",
     "detail": f"{mediator} should be measured after {exposure} and before {outcome}; otherwise the indirect effect has no causal meaning."},
]

# %% Result
labels = {"acme_control": "ACME (control)", "acme_treated": "ACME (treated)", "ade_control": "ADE (control)", "ade_treated": "ADE (treated)",
          "acme": "ACME (average)", "ade": "ADE (average)", "total": "Total effect", "prop_mediated": "Proportion mediated"}
order = ["acme_control", "acme_treated", "ade_control", "ade_treated", "acme", "ade", "total", "prop_mediated"] if interaction else ["acme", "ade", "total", "prop_mediated"]


def fin(v):
    return None if v is None or not np.isfinite(v) else float(v)


effect_rows = [{"effect": labels[k], "estimate": fin(point[k]), "ci_low": fin(summ[k]["ci_low"]), "ci_high": fin(summ[k]["ci_high"]), "p": fin(summ[k]["p"])} for k in order]
values = {"n": n, "x0": x0, "x1": x1, "interaction": interaction, "ci_method": ci_method, "sims": sims if ci_method != "delta" else None,
          "n_used": n_used, "n_failed": n_failed, "a": a, "a_se": a_se, "a_p": a_p, "b": b, "b_se": b_se, "b_p": b_p,
          "c_prime": c_prime, "c_prime_se": c_se, "c_prime_p": c_p, "xm": xm, "xm_se": xm_se, "xm_p": xm_p, "sobel_z": sobel_z, "sobel_p": sobel_p,
          "missing_share": n_dropped / n_input if n_input else 0.0}
for k in labels:
    values[k] = fin(point[k])
    if k in ("acme", "ade", "total", "prop_mediated"):
        values.update({f"{k}_ci_low": fin(summ[k]["ci_low"]), f"{k}_ci_high": fin(summ[k]["ci_high"]), f"{k}_p": fin(summ[k]["p"])})
    else:
        values.update({f"{k}_ci_low": fin(summ[k]["ci_low"]), f"{k}_ci_high": fin(summ[k]["ci_high"])})
paths = [
    {"path": f"a: {exposure} → {mediator}", "estimate": a, "se": a_se, "t": a_t, "p": a_p},
    {"path": f"b: {mediator} → {outcome} (given {exposure})", "estimate": b, "se": b_se, "t": b_t, "p": b_p},
    {"path": f"c′: {exposure} → {outcome} (direct)", "estimate": c_prime, "se": c_se, "t": c_t, "p": c_p},
] + ([{"path": f"{exposure} × {mediator}", "estimate": xm, "se": xm_se, "t": xm_t, "p": xm_p}] if interaction else [])
method_name = {"bootstrap": f"nonparametric bootstrap ({n_used} of {sims} resamples, percentile intervals)",
               "quasi_bayes": f"quasi-Bayesian simulation ({sims} draws, percentile intervals)",
               "delta": "delta method (normal approximation)"}[ci_method]
pct = f"{conf:.0%}"
pm = point["prop_mediated"]
summary = (f"Effect of {exposure} ({contrast}) on {outcome} through {mediator} (n = {n}): ACME = {point['acme']:.3f} "
           f"[{summ['acme']['ci_low']:.3f}, {summ['acme']['ci_high']:.3f}], {cs.fmt_p(summ['acme']['p'])}; ADE = {point['ade']:.3f}; "
           f"total = {point['total']:.3f}" + (f"; proportion mediated {pm:.2f}." if np.isfinite(pm) else "."))
cs.publish({
    "method": "regression.mediation",
    "methodVersion": "1.0.1",
    "title": "Mediation analysis",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"ACME = {point['acme']:.2f}, {pct} CI [{summ['acme']['ci_low']:.2f}, {summ['acme']['ci_high']:.2f}], {cs.fmt_p(summ['acme']['p'])}",
    "statistics": [{"key": "acme", "label": "ACME (indirect)", "value": fin(point["acme"])}, {"key": "acme_p", "label": "p", "value": fin(summ["acme"]["p"]), "format": "p"},
                   {"key": "ade", "label": "ADE (direct)", "value": fin(point["ade"])}, {"key": "total", "label": "Total", "value": fin(point["total"])},
                   {"key": "prop_mediated", "label": "Proportion mediated", "value": fin(pm)}],
    "tables": [
        {"key": "effects", "title": f"Effects of {exposure} ({contrast})", "columns": [
            {"key": "effect", "label": "Effect", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
            {"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"},
            {"key": "p", "label": "p", "type": "pvalue"}],
         "rows": effect_rows, "note": "ACME: the change in the outcome when only the mediator moves as the exposure would move it; ADE: the change with the mediator held fixed."},
        {"key": "paths", "title": "Model paths", "columns": [
            {"key": "path", "label": "Path", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"},
            {"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
         "rows": paths},
    ],
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings + ([f"{n_failed} resamples lost a variable's variation and were skipped."] if n_failed else []),
    "notes": [f"Linear mediator and outcome models (OLS){', outcome model with the exposure × mediator interaction' if interaction else ''}; covariates at their sample means. Intervals: {method_name}."
              + (f" Seed {seed}: the same draws in Python and R." if ci_method != "delta" else "")],
    "charts": [cs.chart("effects", "forest", "Indirect, direct and total effects", {
        "label": cs.col("Effect", [r["effect"] for r in effect_rows if r["effect"] != "Proportion mediated"], kind="categorical"),
        "estimate": cs.col("Estimate", [r["estimate"] for r in effect_rows if r["effect"] != "Proportion mediated"]),
        "low": cs.col("low", [r["ci_low"] for r in effect_rows if r["effect"] != "Proportion mediated"]),
        "high": cs.col("high", [r["ci_high"] for r in effect_rows if r["effect"] != "Proportion mediated"])}, controls={"reference": 0})],
    "values": values,
})
09

Check your understanding

Checkpoint

Check yourself

A drug's effect is larger in older patients. What does age do here?

Show the answer

Answer: a

Moderation changes the size of an effect. Mediation would need age to lie on the path from drug to outcome, which it can't.

Check yourself

Treatment was randomized, and you estimate its indirect effect through a mediator. What remains an assumption?

Show the answer

Answer: b

Randomizing the treatment doesn't randomize the mediator. People's mediator values can still be confounded with their outcomes, and the data can't test that.

Check yourself

In y = 10 − 3x + 2g − 2(x × g), with g coded 0/1, what is the slope of x when g = 1?

Show the answer

Answer: -5

The slope is β1 + β3 = −3 + (−2) = −5.

Check yourself

A model has age, treatment and age × treatment. Age isn't centered. What does the treatment coefficient mean?

Show the answer

Answer: b

Once an interaction is present, a lower-order term is the effect where the other variable equals zero. Center age to get the effect at the mean age.

Check yourself

The interaction test gives p = .30 in a small study. What can you conclude?

Show the answer

Answer: b

Interactions have low power. A large p-value doesn't show the slopes are the same.

10

Do it on your own data

In the app

Put the two interacting predictors first, then set Interactions to "First two predictors (A × B)". The card adds simple slopes, and Johnson–Neyman boundaries when both predictors are numeric.

Python
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("mtcars.csv")
df["wt_c"] = df["wt"] - df["wt"].mean()
fit = smf.ols("mpg ~ wt_c * am_f", data=df).fit()
print(fit.summary())
R
df <- read.csv("mtcars.csv")
df$wt_c <- df$wt - mean(df$wt)
fit <- lm(mpg ~ wt_c * am_f, data = df)
summary(fit)
11

Recap

Recap
  • An interaction term is the difference between slopes.
  • With an interaction in the model, lower-order terms are effects at zero of the other variable: center first.
  • Read simple slopes or Johnson–Neyman boundaries, and check the data overlap.
  • Interactions need many rows, so a large p-value doesn't show parallel slopes.

Concepts in this lesson