Random intercepts and partial pooling
A separate mean for each group trusts small groups too much, and one mean for all ignores them. A random intercept sits between the two, pulling each group toward the rest by an amount the data decide.
What runs in CodeSplash
- Linear mixed model (random intercepts and slopes) Verified in Python and R
You will be able to
- Compare complete, no and partial pooling
- Write a random-intercept model and say what each part estimates
- Say which groups shrink most, and why
- Read variance components, ICC and the two R² values from a card
Three ways to treat groups
ReadYou want the mean outcome in each of 15 schools.
- Complete pooling: ignore schools and use one mean. Every school gets the same answer, and real differences vanish.
- No pooling: use each school's own mean. A school with four pupils gets an estimate as noisy as those four pupils.
- Partial pooling: estimate each school's mean as a weighted blend of its own data and the overall mean.
Who moves most?
PredictPredict first
Two schools have the same mean, both well above average. Under partial pooling, whose estimate moves further toward the overall mean?
Reveal
The small one. Its own mean is noisy, so it borrows more from the other schools. The large school has plenty of its own data and barely moves.
Move the sliders
ExploreDExplorable · Partial pooling
How can small groups borrow strength from the rest of the data?
Which estimate gets closest to the truth?
Thicker lines are larger groups: they move little. Small groups shrink the most toward the overall mean.
Commit your prediction above to see the result
Make your prediction to see the result.
Set True spread between groups to 0. Partial pooling collapses toward one mean, which is right here. Raise it well above the Noise within groups, and each group keeps nearly its own mean.
Compare the three errors. Across most settings, partial pooling beats both extremes, because it lets the data choose the blend.
The weight
ReadA group's estimate blends its own mean with the overall mean:
is the variance between groups, and is the variance within. A small group, or little real spread between groups, gives a small and more shrinkageShrinkagePulling a noisy group estimate toward the overall mean, by more when the group is small or groups barely differ..
The model learns from all the groups together. That's the sense in which they share strength.
Writing the model
ReadA mixed modelMixed modelRegression with random effects for groups (people, schools, sites), so repeated or clustered data are analyzed correctly. has two kinds of term:
Fixed effectsFixed effectAn effect estimated with its own parameter; in panel data, unit fixed effects absorb all stable differences between units. are the averages you want to report. The random effectRandom effectGroup-level variation modeled as draws from a distribution rather than one parameter per group. is one group's departure from them. You don't estimate each as a free parameter: you estimate , and the follow from it.
Read the card
In the appF(1, 786.04) = 43098.70, p < .001
- ICC (adjusted)
- 0.7772
- R² marginal
- 0.9184
- R² conditional
- 0.9818
- Residual SD
- 3.374
- AIC
- 4799.32
Assumptions
- Normal residuals — Shapiro–Wilk W = 0.960, p < .001 on the conditional residuals (with many rows small departures are flagged; look at the Q–Q plot).
- Normal random effects (pig: (Intercept)) — Shapiro–Wilk W = 0.953, p = .009 on 72 conditional modes.
- Non-singular fit — Every variance component is clearly above zero.
- Enough groups — 72 levels of pig.
Fixed effects
| Term | B | SE | df | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | 15.092 | 1.753 | 69.114 | 8.607 | < .001 | 11.594 | 18.590 |
| week | 6.942 | 0.0334 | 786.04 | 207.60 | < .001 | 6.876 | 7.007 |
| copper: Cu035 | −0.7575 | 1.843 | 67.016 | −0.4109 | .682 | −4.437 | 2.922 |
| copper: Cu175 | 1.795 | 1.862 | 67.022 | 0.9640 | .338 | −1.921 | 5.511 |
| vitamin E: Evit100 | 2.049 | 1.862 | 67.015 | 1.101 | .275 | −1.667 | 5.765 |
| vitamin E: Evit200 | −1.103 | 1.843 | 67.008 | −0.5982 | .552 | −4.782 | 2.577 |
t tests with Satterthwaite degrees of freedom (lmerTest).
Joint tests of each predictor
| Term | F | num df | den df | p |
|---|---|---|---|---|
| week | 43098.70 | 1 | 786.04 | < .001 |
| copper | 1.027 | 2 | 67.011 | .364 |
| vitamin E | 1.531 | 2 | 67.010 | .224 |
All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest).
Random effects
| Group | Effect | Variance | SD | Correlation |
|---|---|---|---|---|
| pig | (Intercept) | 39.727 | 6.303 | — |
| Residual | 11.386 | 3.374 | — |
Conditional modes of the random effects
| Group | Effect | Level | Mode | Conditional SD |
|---|---|---|---|---|
| pig | (Intercept) | 4601 | −0.8185 | 1.004 |
| pig | (Intercept) | 4602 | 4.447 | 0.9626 |
| pig | (Intercept) | 4603 | 3.927 | 0.9626 |
| pig | (Intercept) | 4605 | 6.150 | 0.9626 |
| pig | (Intercept) | 4641 | 6.017 | 0.9626 |
| pig | (Intercept) | 4643 | 1.510 | 0.9626 |
| pig | (Intercept) | 4645 | 6.859 | 0.9626 |
| pig | (Intercept) | 4756 | −9.752 | 0.9626 |
| pig | (Intercept) | 4757 | 1.453 | 0.9626 |
| pig | (Intercept) | 4759 | −0.6449 | 0.9626 |
| pig | (Intercept) | 4760 | −20.932 | 0.9626 |
| pig | (Intercept) | 4813 | 3.861 | 0.9626 |
| pig | (Intercept) | 4814 | −1.005 | 0.9626 |
| pig | (Intercept) | 4815 | −3.831 | 0.9626 |
| pig | (Intercept) | 4817 | 1.230 | 0.9626 |
| pig | (Intercept) | 4854 | −2.566 | 0.9626 |
| pig | (Intercept) | 4856 | 7.053 | 0.9626 |
| pig | (Intercept) | 4857 | 0.7989 | 0.9626 |
| pig | (Intercept) | 4858 | 1.698 | 0.9626 |
| pig | (Intercept) | 5389 | −4.765 | 0.9626 |
| pig | (Intercept) | 5392 | −8.352 | 0.9626 |
| pig | (Intercept) | 5497 | −4.016 | 0.9626 |
| pig | (Intercept) | 5500 | −12.636 | 0.9626 |
| pig | (Intercept) | 5501 | 2.941 | 0.9626 |
| pig | (Intercept) | 5502 | 7.479 | 0.9626 |
| pig | (Intercept) | 5524 | −7.610 | 1.004 |
| pig | (Intercept) | 5527 | −3.884 | 1.004 |
| pig | (Intercept) | 5528 | 0.9370 | 1.004 |
| pig | (Intercept) | 5578 | 3.990 | 0.9626 |
| pig | (Intercept) | 5581 | 4.068 | 0.9626 |
| pig | (Intercept) | 5582 | 1.974 | 0.9626 |
| pig | (Intercept) | 5850 | −4.331 | 0.9626 |
| pig | (Intercept) | 5851 | −2.780 | 0.9626 |
| pig | (Intercept) | 5852 | 4.061 | 1.004 |
| pig | (Intercept) | 5862 | −5.661 | 0.9626 |
| pig | (Intercept) | 5865 | −2.240 | 0.9626 |
| pig | (Intercept) | 5866 | −9.569 | 0.9626 |
| pig | (Intercept) | 6055 | 3.661 | 0.9626 |
| pig | (Intercept) | 6056 | 13.034 | 0.9626 |
| pig | (Intercept) | 6057 | 1.598 | 0.9626 |
First 40 of 72 rows.
- 2 of 861 rows were left out because a value was missing.
- REML fit with lme4::lmer; fixed effects tested with Satterthwaite df (lmerTest).
The exact R script · R R version 4.5.1 (2025-06-13)
# Linear mixed model (random intercepts and slopes)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.lmm 1.0.1 · spec 9be23ec273c038af
# Dataset: s1_dietox (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
suppressPackageStartupMessages({
library(lme4)
library(lmerTest) # Satterthwaite degrees of freedom
})
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_dietox.parquet", col_select = c("weight", "week", "copper", "vitamin E", "pig")))
n_input <- nrow(df)
df[["copper"]] <- factor(df[["copper"]], levels = c("Cu000", "Cu035", "Cu175")) # stored level order
df[["vitamin E"]] <- factor(df[["vitamin E"]], levels = c("Evit000", "Evit100", "Evit200")) # stored level order
df[["pig"]] <- factor(df[["pig"]], levels = c("4601", "4602", "4603", "4605", "4641", "4643", "4645", "4756", "4757", "4759", "4760", "4813", "4814", "4815", "4817", "4854", "4856", "4857", "4858", "5389", "5392", "5497", "5500", "5501", "5502", "5524", "5527", "5528", "5578", "5581", "5582", "5850", "5851", "5852", "5862", "5865", "5866", "6055", "6056", "6057", "6058", "6207", "6208", "6211", "6284", "6287", "6288", "6430", "6432", "6433", "6909", "6910", "6912", "8049", "8050", "8051", "8053", "8139", "8141", "8142", "8144", "8191", "8192", "8193", "8195", "8269", "8270", "8271", "8273", "8437", "8439", "8442")) # stored level order
df <- df[stats::complete.cases(df[c("weight", "week", "copper", "vitamin E", "pig")]), , 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("weight", "week", "copper", "vitamin E", "pig")) # infinite values stop the run (registry/errors.yaml)
# %% Model
outcome <- "weight"
predictors <- c("week", "copper", "vitamin E")
group <- "pig"
slopes <- c()
group2 <- NULL
nesting <- "nested" # nested: (1 | group/group2); crossed: (1 | group2)
correlated <- "correlated" == "correlated" # (1 + x | g) vs (1 + x || g)
interactions <- "none"
reml <- "reml" == "reml"
conf <- 0.95
df[[group]] <- cs_mixed_group(df[[group]])
if (!is.null(group2)) df[[group2]] <- cs_mixed_group(df[[group2]])
# Degenerate input stops with a catalog error before the fit; Python runs the same checks in the same order.
cs_mixed_check_re(df, group, slopes, group2, nesting, correlated) # lme4's checks on the grouping factors
if (length(unique(df[[outcome]])) < 2) cs_error("CS_E_CONSTANT", column = outcome)
for (pred in predictors) {
if (length(unique(df[[pred]])) < 2) cs_error("CS_E_CONSTANT", column = pred) # one value (or one level with data) is no variation
}
fml <- cs_mixed_formula(outcome, predictors, interactions, group, slopes, group2, nesting, correlated)
# Tight optimizer tolerance so the variance parameters are found to ~1e-10 (lme4's default stops near 1e-5).
ctrl <- lmerControl(optimizer = "bobyqa", optCtrl = list(rhoend = 1e-12, maxfun = 1e6))
# %% Fit
fit <- lmerTest::lmer(fml, data = df, REML = reml, control = ctrl)
X <- getME(fit, "X")
terms_x <- cs_design_labels(df, predictors, interactions)
if (ncol(X) < length(terms_x)) cs_error("CS_E_COLLINEAR")
n <- nrow(X)
k <- ncol(X)
y <- df[[outcome]]
ct <- summary(fit)$coefficients # Estimate, SE, df (Satterthwaite), t, p
values <- list()
coefs <- list()
for (j in seq_len(k)) {
est <- ct[j, "Estimate"]; se <- ct[j, "Std. Error"]; ddf <- ct[j, "df"]; tval <- ct[j, "t value"]; pval <- ct[j, "Pr(>|t|)"]
q <- qt(1 - (1 - conf) / 2, ddf)
term <- terms_x[j]
coefs[[j]] <- list(term = term, estimate = est, se = se, df = ddf, t = tval, p = pval, ci_low = est - q * se, ci_high = est + q * se)
values[[sprintf("coef[%s]", term)]] <- est; values[[sprintf("se[%s]", term)]] <- se; values[[sprintf("df[%s]", term)]] <- ddf
values[[sprintf("t[%s]", term)]] <- tval; values[[sprintf("p[%s]", term)]] <- pval
values[[sprintf("ci_low[%s]", term)]] <- est - q * se; values[[sprintf("ci_high[%s]", term)]] <- est + q * se
}
effects <- list()
blocks <- cs_mixed_term_blocks(terms_x, predictors, interactions)
for (name in names(blocks)) {
L <- diag(k)[blocks[[name]], , drop = FALSE]
tt <- lmerTest::contest(fit, L, joint = TRUE) # Satterthwaite F test of all the term's coefficients
e <- list(term = name, f = tt[["F value"]], df1 = tt[["NumDF"]], df2 = tt[["DenDF"]], p = tt[["Pr(>F)"]])
effects[[length(effects) + 1]] <- e
values[[sprintf("f[%s]", name)]] <- e$f; values[[sprintf("f_df1[%s]", name)]] <- as.numeric(e$df1)
values[[sprintf("f_df2[%s]", name)]] <- e$df2; values[[sprintf("f_p[%s]", name)]] <- e$p
}
values$focal_f <- NA; values$focal_df1 <- NA; values$focal_df2 <- NA; values$focal_p <- NA # no fixed predictor
if (length(effects)) {
values$focal_f <- effects[[1]]$f; values$focal_df1 <- as.numeric(effects[[1]]$df1)
values$focal_df2 <- effects[[1]]$df2; values$focal_p <- effects[[1]]$p
}
# %% Variance components, ICC and R² (Nakagawa; random slopes as Johnson 2014)
valid <- c(group, group2, if (!is.null(group2)) paste0(group, ":", group2))
vc <- cs_mixed_varcorr(fit, valid)
for (i in seq_len(nrow(vc))) {
if (is.na(vc$effect2[i])) {
values[[sprintf("var[%s|%s]", vc$group[i], vc$effect1[i])]] <- vc$vcov[i]
values[[sprintf("sd[%s|%s]", vc$group[i], vc$effect1[i])]] <- vc$sdcor[i]
} else {
values[[sprintf("cor[%s|%s|%s]", vc$group[i], vc$effect1[i], vc$effect2[i])]] <- vc$sdcor[i]
}
}
sig <- sigma(fit)
sigma2 <- sig^2
var_fixed <- if (n > 1) var(as.vector(X %*% fixef(fit))) else 0
var_random <- cs_mixed_random_variance(fit, df)
icc <- var_random / (var_random + sigma2)
total <- var_fixed + var_random + sigma2
n_theta <- length(getME(fit, "theta"))
n_params <- k + n_theta + 1
crit <- if (reml) REMLcrit(fit) else deviance(fit)
n_groups <- nlevels(droplevels(df[[group]]))
values <- c(values, list(n = n, k = k, n_groups = n_groups, sigma = sig, log_lik = as.numeric(logLik(fit)), deviance = crit,
aic = crit + 2 * n_params, bic = crit + log(n) * n_params, icc = icc, r2_marginal = var_fixed / total,
r2_conditional = (var_fixed + var_random) / total, var_fixed = var_fixed, var_random = var_random,
singular = isSingular(fit, tol = 1e-4), n_params = n_params, n_theta = n_theta,
max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1,
missing_share = if (n_input > 0) n_dropped / n_input else 0, reml = reml))
if (!is.null(group2)) {
values$n_groups2 <- if (nesting == "nested") nlevels(droplevels(interaction(df[[group]], df[[group2]], drop = TRUE))) else nlevels(droplevels(df[[group2]]))
}
# %% Random effects vs none (likelihood ratio, ML)
if (FALSE) {
ml <- if (reml) update(fit, REML = FALSE) else fit
fixed_fml <- if (length(predictors)) cs_model_formula(outcome, predictors, interactions) else stats::as.formula(paste0("`", outcome, "` ~ 1"))
ll_lm <- as.numeric(logLik(lm(fixed_fml, data = df)))
lrt <- max(2 * (as.numeric(logLik(ml)) - ll_lm), 0)
lrt_p <- pchisq(lrt, n_theta, lower.tail = FALSE)
if (n_theta == 1) lrt_p <- lrt_p / 2 # one variance component on its boundary: 50:50 mixture of chi2(0) and chi2(1)
values$re_lrt <- lrt; values$re_lrt_df <- as.numeric(n_theta); values$re_lrt_p <- lrt_p
}
# %% Assumptions
assumptions <- list()
resid <- residuals(fit)
if (n >= 3 && n <= 5000) {
sw <- shapiro.test(resid)
values$sw_p_resid <- sw$p.value
status <- if (sw$p.value >= 0.05) "pass" else if (n < 300) "warn" else "info"
assumptions[[length(assumptions) + 1]] <- list(key = "normality", label = "Normal residuals", status = status, statistic = unname(sw$statistic), p = sw$p.value,
detail = paste0(sprintf("Shapiro–Wilk W = %.3f, %s on the conditional residuals", sw$statistic, cs_fmt_p(sw$p.value)),
if (n >= 300) " (with many rows small departures are flagged; look at the Q–Q plot)." else "."))
}
re_tab <- cs_mixed_ranef(fit, valid)
for (key in unique(paste(re_tab$group, re_tab$effect, sep = "\r"))) {
sel <- paste(re_tab$group, re_tab$effect, sep = "\r") == key
b <- re_tab$estimate[sel]
if (length(b) >= 8 && diff(range(b)) > 0) {
swr <- shapiro.test(b)
assumptions[[length(assumptions) + 1]] <- list(key = "re_normality", label = sprintf("Normal random effects (%s: %s)", re_tab$group[sel][1], re_tab$effect[sel][1]),
status = if (swr$p.value >= 0.05) "pass" else "warn", statistic = unname(swr$statistic), p = swr$p.value,
detail = sprintf("Shapiro–Wilk W = %.3f, %s on %d conditional modes.", swr$statistic, cs_fmt_p(swr$p.value), length(b)))
}
}
singular <- isTRUE(values$singular)
assumptions[[length(assumptions) + 1]] <- list(key = "singular", label = "Non-singular fit", status = if (singular) "warn" else "pass",
detail = if (singular) "A variance component is estimated at (or near) zero: simplify the random effects (drop a slope or the correlation)." else "Every variance component is clearly above zero.")
nlev <- c(setNames(n_groups, group), if (!is.null(group2)) setNames(values$n_groups2, if (nesting == "nested") paste0(group, ":", group2) else group2))
few <- names(nlev)[nlev < 5]
assumptions[[length(assumptions) + 1]] <- list(key = "groups", label = "Enough groups", status = if (length(few)) "warn" else "pass",
detail = if (length(few)) sprintf("Fewer than 5 levels for %s: its variance is estimated very imprecisely.", paste(few, collapse = ", ")) else sprintf("%d levels of %s.", n_groups, group))
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
slopes_tab <- if (length(terms_x) && terms_x[1] == "(Intercept)") coefs[-1] else coefs
vc_rows <- lapply(seq_len(nrow(vc)), function(i) {
if (is.na(vc$effect2[i])) list(group = vc$group[i], effect = vc$effect1[i], variance = vc$vcov[i], sd = vc$sdcor[i], cor = NULL)
else list(group = vc$group[i], effect = paste(vc$effect1[i], "~", vc$effect2[i]), variance = NULL, sd = NULL, cor = vc$sdcor[i])
})
vc_rows[[length(vc_rows) + 1]] <- list(group = "Residual", effect = "", variance = sigma2, sd = sig, cor = NULL)
tests_text <- if (length(effects)) sprintf(" %s: F(%d, %.1f) = %.2f, %s.", effects[[1]]$term, as.integer(effects[[1]]$df1), effects[[1]]$df2, effects[[1]]$f, cs_fmt_p(effects[[1]]$p)) else ""
summary <- sprintf("Linear mixed model (%s) of %s (n = %d, %d levels of %s).%s Adjusted ICC = %.2f; marginal R² = %.2f, conditional R² = %.2f.",
if (reml) "REML" else "ML", outcome, n, n_groups, group, tests_text, icc, var_fixed / total, (var_fixed + var_random) / total)
z <- qnorm(1 - (1 - conf) / 2)
cat_tab <- head(re_tab, 1000)
charts <- list(
cs_chart("ranef", "caterpillar", "Random effects (conditional modes)", list(
group = cs_col("Level", cat_tab$level, kind = "categorical"), estimate = cs_col("Conditional mode", cat_tab$estimate),
low = cs_col("low", cat_tab$estimate - z * cat_tab$sd), high = cs_col("high", cat_tab$estimate + z * cat_tab$sd),
term = cs_col("Term", paste0(cat_tab$group, ": ", cat_tab$effect), kind = "categorical"))),
cs_chart("residuals", "residual-panel", "Residual diagnostics", list(fitted = cs_col("Fitted", unname(fitted(fit))), residual = cs_col("Residual", unname(resid))))
)
if (length(slopes_tab)) {
charts[[length(charts) + 1]] <- cs_chart("coef", "forest", "Fixed effects", list(
label = cs_col("Term", vapply(slopes_tab, `[[`, "", "term"), kind = "categorical"), estimate = cs_col("Estimate", vapply(slopes_tab, `[[`, 0, "estimate")),
low = cs_col("low", vapply(slopes_tab, `[[`, 0, "ci_low")), high = cs_col("high", vapply(slopes_tab, `[[`, 0, "ci_high"))), controls = list(reference = 0))
}
tables <- list(list(key = "fixed", title = "Fixed effects", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "df", label = "df", 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 = coefs, note = "t tests with Satterthwaite degrees of freedom (lmerTest)."))
if (length(effects)) {
tables[[length(tables) + 1]] <- list(key = "effects", title = "Joint tests of each predictor", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "f", label = "F", type = "number"), list(key = "df1", label = "num df", type = "integer"),
list(key = "df2", label = "den df", type = "number"), list(key = "p", label = "p", type = "pvalue")),
rows = effects, note = "All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest).")
}
tables[[length(tables) + 1]] <- list(key = "random", title = "Random effects", columns = list(
list(key = "group", label = "Group", type = "string"), list(key = "effect", label = "Effect", type = "string"),
list(key = "variance", label = "Variance", type = "number"), list(key = "sd", label = "SD", type = "number"), list(key = "cor", label = "Correlation", type = "number")),
rows = vc_rows)
mode_rows <- lapply(seq_len(min(nrow(re_tab), 2000)), function(i) as.list(re_tab[i, ]))
tables[[length(tables) + 1]] <- list(key = "modes", title = "Conditional modes of the random effects", columns = list(
list(key = "group", label = "Group", type = "string"), list(key = "effect", label = "Effect", type = "string"), list(key = "level", label = "Level", type = "string"),
list(key = "estimate", label = "Mode", type = "number"), list(key = "sd", label = "Conditional SD", type = "number")), rows = mode_rows)
statistics <- list(list(key = "icc", label = "ICC (adjusted)", value = icc), list(key = "r2_marginal", label = "R² marginal", value = var_fixed / total),
list(key = "r2_conditional", label = "R² conditional", value = (var_fixed + var_random) / total), list(key = "sigma", label = "Residual SD", value = sig),
list(key = "aic", label = "AIC", value = crit + 2 * n_params))
if (!is.null(values$re_lrt_p)) statistics[[length(statistics) + 1]] <- list(key = "re_lrt_p", label = "Random effects LR test p", value = values$re_lrt_p, format = "p")
cs_publish(list(
method = "mixed.lmm",
methodVersion = "1.0.1",
title = "Linear mixed model",
engine = cs_engine_info("lme4", "lmerTest", "nanoparquet"),
n = n,
summary = summary,
apa = if (length(effects)) sprintf("F(%d, %.2f) = %.2f, %s", as.integer(effects[[1]]$df1), effects[[1]]$df2, effects[[1]]$f, cs_fmt_p(effects[[1]]$p)) else "",
statistics = statistics,
tables = tables,
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("%s fit with lme4::lmer; fixed effects tested with Satterthwaite df (lmerTest).", if (reml) "REML" else "Maximum likelihood")),
charts = charts,
values = values
))
F(1, 786.04) = 43098.70, p < .001
- ICC (adjusted)
- 0.7772
- R² marginal
- 0.9184
- R² conditional
- 0.9818
- Residual SD
- 3.374
- AIC
- 4799.32
Assumptions
- Normal residuals — Shapiro–Wilk W = 0.960, p < .001 on the conditional residuals (with many rows small departures are flagged; look at the Q–Q plot).
- Normal random effects (pig: (Intercept)) — Shapiro–Wilk W = 0.953, p = .009 on 72 conditional modes.
- Non-singular fit — Every variance component is clearly above zero.
- Enough groups — 72 levels of pig.
Fixed effects
| Term | B | SE | df | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | 15.092 | 1.753 | 69.114 | 8.607 | < .001 | 11.594 | 18.590 |
| week | 6.942 | 0.0334 | 786.04 | 207.60 | < .001 | 6.876 | 7.007 |
| copper: Cu035 | −0.7575 | 1.843 | 67.016 | −0.4109 | .682 | −4.437 | 2.922 |
| copper: Cu175 | 1.795 | 1.862 | 67.022 | 0.9640 | .338 | −1.921 | 5.511 |
| vitamin E: Evit100 | 2.049 | 1.862 | 67.015 | 1.101 | .275 | −1.667 | 5.765 |
| vitamin E: Evit200 | −1.103 | 1.843 | 67.008 | −0.5982 | .552 | −4.782 | 2.577 |
t tests with Satterthwaite degrees of freedom (lmerTest).
Joint tests of each predictor
| Term | F | num df | den df | p |
|---|---|---|---|---|
| week | 43098.70 | 1 | 786.04 | < .001 |
| copper | 1.027 | 2 | 67.011 | .364 |
| vitamin E | 1.531 | 2 | 67.010 | .224 |
All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest).
Random effects
| Group | Effect | Variance | SD | Correlation |
|---|---|---|---|---|
| pig | (Intercept) | 39.727 | 6.303 | — |
| Residual | 11.386 | 3.374 | — |
Conditional modes of the random effects
| Group | Effect | Level | Mode | Conditional SD |
|---|---|---|---|---|
| pig | (Intercept) | 4601 | −0.8185 | 1.004 |
| pig | (Intercept) | 4602 | 4.447 | 0.9626 |
| pig | (Intercept) | 4603 | 3.927 | 0.9626 |
| pig | (Intercept) | 4605 | 6.150 | 0.9626 |
| pig | (Intercept) | 4641 | 6.017 | 0.9626 |
| pig | (Intercept) | 4643 | 1.510 | 0.9626 |
| pig | (Intercept) | 4645 | 6.859 | 0.9626 |
| pig | (Intercept) | 4756 | −9.752 | 0.9626 |
| pig | (Intercept) | 4757 | 1.453 | 0.9626 |
| pig | (Intercept) | 4759 | −0.6449 | 0.9626 |
| pig | (Intercept) | 4760 | −20.932 | 0.9626 |
| pig | (Intercept) | 4813 | 3.861 | 0.9626 |
| pig | (Intercept) | 4814 | −1.005 | 0.9626 |
| pig | (Intercept) | 4815 | −3.831 | 0.9626 |
| pig | (Intercept) | 4817 | 1.230 | 0.9626 |
| pig | (Intercept) | 4854 | −2.566 | 0.9626 |
| pig | (Intercept) | 4856 | 7.053 | 0.9626 |
| pig | (Intercept) | 4857 | 0.7989 | 0.9626 |
| pig | (Intercept) | 4858 | 1.698 | 0.9626 |
| pig | (Intercept) | 5389 | −4.765 | 0.9626 |
| pig | (Intercept) | 5392 | −8.352 | 0.9626 |
| pig | (Intercept) | 5497 | −4.016 | 0.9626 |
| pig | (Intercept) | 5500 | −12.636 | 0.9626 |
| pig | (Intercept) | 5501 | 2.941 | 0.9626 |
| pig | (Intercept) | 5502 | 7.479 | 0.9626 |
| pig | (Intercept) | 5524 | −7.610 | 1.004 |
| pig | (Intercept) | 5527 | −3.884 | 1.004 |
| pig | (Intercept) | 5528 | 0.9370 | 1.004 |
| pig | (Intercept) | 5578 | 3.990 | 0.9626 |
| pig | (Intercept) | 5581 | 4.068 | 0.9626 |
| pig | (Intercept) | 5582 | 1.974 | 0.9626 |
| pig | (Intercept) | 5850 | −4.331 | 0.9626 |
| pig | (Intercept) | 5851 | −2.780 | 0.9626 |
| pig | (Intercept) | 5852 | 4.061 | 1.004 |
| pig | (Intercept) | 5862 | −5.661 | 0.9626 |
| pig | (Intercept) | 5865 | −2.240 | 0.9626 |
| pig | (Intercept) | 5866 | −9.569 | 0.9626 |
| pig | (Intercept) | 6055 | 3.661 | 0.9626 |
| pig | (Intercept) | 6056 | 13.034 | 0.9626 |
| pig | (Intercept) | 6057 | 1.598 | 0.9626 |
First 40 of 72 rows.
- 2 of 861 rows were left out because a value was missing.
- REML fit of lme4's model (twin of lme4's profiled deviance); fixed effects tested with Satterthwaite df (lmerTest).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Linear mixed model (random intercepts and slopes)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.lmm 1.0.1 · spec 9be23ec273c038af
# Dataset: s1_dietox (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.stats import mixed as mx # twin of lme4 + lmerTest (statsmodels' MixedLM has no Satterthwaite df)
from codesplash.stats import regression as csreg
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s1_dietox.parquet", columns=["weight", "week", "copper", "vitamin E", "pig"])
n_input = len(df)
df["copper"] = pd.Categorical(df["copper"], categories=["Cu000", "Cu035", "Cu175"]) # stored level order
df["vitamin E"] = pd.Categorical(df["vitamin E"], categories=["Evit000", "Evit100", "Evit200"]) # stored level order
df["pig"] = pd.Categorical(df["pig"], categories=["4601", "4602", "4603", "4605", "4641", "4643", "4645", "4756", "4757", "4759", "4760", "4813", "4814", "4815", "4817", "4854", "4856", "4857", "4858", "5389", "5392", "5497", "5500", "5501", "5502", "5524", "5527", "5528", "5578", "5581", "5582", "5850", "5851", "5852", "5862", "5865", "5866", "6055", "6056", "6057", "6058", "6207", "6208", "6211", "6284", "6287", "6288", "6430", "6432", "6433", "6909", "6910", "6912", "8049", "8050", "8051", "8053", "8139", "8141", "8142", "8144", "8191", "8192", "8193", "8195", "8269", "8270", "8271", "8273", "8437", "8439", "8442"]) # stored level order
df = df.dropna(subset=["weight", "week", "copper", "vitamin E", "pig"]) # listwise deletion over the analysis columns
df["copper"] = df["copper"].cat.remove_unused_categories()
df["vitamin E"] = df["vitamin E"].cat.remove_unused_categories()
df["pig"] = df["pig"].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, ["weight", "week", "copper", "vitamin E", "pig"]) # infinite values stop the run (registry/errors.yaml)
# %% Model
outcome = "weight"
predictors = ["week", "copper", "vitamin E"]
group = "pig"
slopes = []
group2 = None
nesting = "nested" # nested: (1 | group/group2); crossed: (1 | group2)
correlated = "correlated" == "correlated" # (1 + x | g) vs (1 + x || g)
interactions = "none"
reml = "reml" == "reml"
conf = 0.95
re = mx.re_terms(df, group, slopes, group2, nesting, correlated)
# Degenerate input stops with a catalog error before the fit; R runs the same checks in the same order.
mx.check_re_terms(re, len(df)) # lme4's checks on the grouping factors
if df[outcome].nunique() < 2:
cs.cs_error("CS_E_CONSTANT", column=outcome)
for pred in predictors:
if df[pred].nunique() < 2: # one value (or one level with data) is no variation
cs.cs_error("CS_E_CONSTANT", column=pred)
X = csreg.design_matrix(df, predictors, interactions) # treatment contrasts, R's column order
terms_x = list(X.columns)
y = df[outcome].to_numpy(dtype=float)
n, k = X.shape
# %% Fit (lme4's profiled deviance; Satterthwaite df as lmerTest)
model = mx.Lmm(y, X.to_numpy(), re)
fit = model.fit(reml)
satt = model.satterthwaite(fit)
values = {}
coefs = []
for j, term in enumerate(terms_x):
est, se, ddf, tval, pval = satt.test1d(np.eye(k)[j])
q = stats.t.ppf(1 - (1 - conf) / 2, ddf)
coefs.append({"term": term, "estimate": est, "se": se, "df": ddf, "t": tval, "p": pval, "ci_low": est - q * se, "ci_high": est + q * se})
values.update({f"coef[{term}]": est, f"se[{term}]": se, f"df[{term}]": ddf, f"t[{term}]": tval, f"p[{term}]": pval,
f"ci_low[{term}]": est - q * se, f"ci_high[{term}]": est + q * se})
effects = []
for name, idx in mx.term_blocks(terms_x, predictors, csreg.interaction_pairs(len(predictors), interactions)):
F, df1, df2, pF = satt.test_md(np.eye(k)[idx])
effects.append({"term": name, "f": F, "df1": df1, "df2": df2, "p": pF})
values.update({f"f[{name}]": F, f"f_df1[{name}]": float(df1), f"f_df2[{name}]": df2, f"f_p[{name}]": pF})
values.update({"focal_f": None, "focal_df1": None, "focal_df2": None, "focal_p": None}) # no fixed predictor
if effects:
values.update({"focal_f": effects[0]["f"], "focal_df1": float(effects[0]["df1"]), "focal_df2": effects[0]["df2"], "focal_p": effects[0]["p"]})
# %% Variance components, ICC and R² (Nakagawa; random slopes as Johnson 2014)
vc = mx.varcorr(re, fit.theta, fit.sigma)
for r in vc:
if r["var2"] is None:
values[f"var[{r['grp']}|{r['var1']}]"] = r["vcov"]
values[f"sd[{r['grp']}|{r['var1']}]"] = r["sdcor"]
else:
values[f"cor[{r['grp']}|{r['var1']}|{r['var2']}]"] = r["sdcor"]
sigma2 = fit.sigma**2
var_fixed = float(np.var(X.to_numpy() @ fit.beta, ddof=1)) if n > 1 else 0.0
var_random = mx.random_variance(re, fit.theta, fit.sigma)
icc = var_random / (var_random + sigma2)
total = var_fixed + var_random + sigma2
n_theta = len(fit.theta)
n_params = k + n_theta + 1
aic = fit.deviance + 2 * n_params
bic = fit.deviance + np.log(n) * n_params
n_groups = re[0].nlev
values.update({"n": n, "k": k, "n_groups": n_groups, "sigma": fit.sigma, "log_lik": fit.log_lik, "deviance": fit.deviance,
"aic": float(aic), "bic": float(bic), "icc": icc, "r2_marginal": var_fixed / total, "r2_conditional": (var_fixed + var_random) / total,
"var_fixed": var_fixed, "var_random": var_random, "singular": fit.singular, "n_params": n_params, "n_theta": n_theta,
"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, "reml": reml})
if group2:
values["n_groups2"] = re[-1].nlev # levels of the second term (group:group2 combinations when nested, as lme4)
# %% Random effects vs none (likelihood ratio, ML)
if False:
ml = model.fit(False) if reml else fit
beta_ols, *_ = np.linalg.lstsq(X.to_numpy(), y, rcond=None)
rss = float(np.sum((y - X.to_numpy() @ beta_ols) ** 2))
ll_lm = -n / 2 * (np.log(2 * np.pi * rss / n) + 1)
lrt = max(2 * (ml.log_lik - ll_lm), 0.0)
lrt_p = float(stats.chi2.sf(lrt, n_theta))
if n_theta == 1:
lrt_p /= 2 # one variance component on its boundary: 50:50 mixture of χ²(0) and χ²(1)
values.update({"re_lrt": lrt, "re_lrt_df": float(n_theta), "re_lrt_p": lrt_p})
# %% Assumptions
assumptions = []
resid = fit.resid
if 3 <= n <= 5000:
sw = stats.shapiro(resid)
values["sw_p_resid"] = float(sw.pvalue)
status = "pass" if sw.pvalue >= 0.05 else ("warn" if n < 300 else "info")
assumptions.append({"key": "normality", "label": "Normal residuals", "status": status, "statistic": float(sw.statistic), "p": float(sw.pvalue),
"detail": f"Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)} on the conditional residuals" + (" (with many rows small departures are flagged; look at the Q–Q plot)." if n >= 300 else ".")})
re_rows = []
off = 0
for ti, t in enumerate(re):
for j, eff in enumerate(t.effects):
b = np.array([fit.b[off + g * t.k + j] for g in range(t.nlev)])
sd = np.array([np.sqrt(max(fit.cond_var[ti][g][j, j], 0.0)) for g in range(t.nlev)])
re_rows += [{"group": t.group, "effect": eff, "level": lv, "estimate": float(bv), "sd": float(sv)} for lv, bv, sv in zip(t.levels, b, sd)]
if t.nlev >= 8 and np.ptp(b) > 0:
swr = stats.shapiro(b)
assumptions.append({"key": "re_normality", "label": f"Normal random effects ({t.group}: {eff})", "status": "pass" if swr.pvalue >= 0.05 else "warn",
"statistic": float(swr.statistic), "p": float(swr.pvalue), "detail": f"Shapiro–Wilk W = {swr.statistic:.3f}, {cs.fmt_p(swr.pvalue)} on {t.nlev} conditional modes."})
off += t.nlev * t.k
assumptions.append({"key": "singular", "label": "Non-singular fit", "status": "warn" if fit.singular else "pass",
"detail": "A variance component is estimated at (or near) zero: simplify the random effects (drop a slope or the correlation)." if fit.singular else "Every variance component is clearly above zero."})
few = [t.group for t in re if t.nlev < 5]
assumptions.append({"key": "groups", "label": "Enough groups", "status": "warn" if few else "pass",
"detail": (f"Fewer than 5 levels for {', '.join(dict.fromkeys(few))}: its variance is estimated very imprecisely." if few else f"{n_groups} levels of {group}.")})
# %% Result
pct = f"{conf:.0%}"
slopes_tab = coefs[1:] if terms_x and terms_x[0] == "(Intercept)" else coefs
vc_rows = [{"group": r["grp"], "effect": r["var1"] if r["var2"] is None else f"{r['var1']} ~ {r['var2']}",
"variance": r["vcov"] if r["var2"] is None else None, "sd": r["sdcor"] if r["var2"] is None else None,
"cor": r["sdcor"] if r["var2"] is not None else None} for r in vc]
vc_rows.append({"group": "Residual", "effect": "", "variance": sigma2, "sd": fit.sigma, "cor": None})
tests_text = ""
if effects:
e0 = effects[0]
tests_text = f" {e0['term']}: F({e0['df1']}, {e0['df2']:.1f}) = {e0['f']:.2f}, {cs.fmt_p(e0['p'])}."
summary = (f"Linear mixed model ({'REML' if reml else 'ML'}) of {outcome} (n = {n}, {n_groups} levels of {group}).{tests_text} "
f"Adjusted ICC = {icc:.2f}; marginal R² = {var_fixed / total:.2f}, conditional R² = {(var_fixed + var_random) / total:.2f}.")
cat_rows = re_rows[:1000]
charts = [
cs.chart("ranef", "caterpillar", "Random effects (conditional modes)", {
"group": cs.col("Level", [r["level"] for r in cat_rows], kind="categorical"),
"estimate": cs.col("Conditional mode", [r["estimate"] for r in cat_rows]),
"low": cs.col("low", [r["estimate"] - stats.norm.ppf(1 - (1 - conf) / 2) * r["sd"] for r in cat_rows]),
"high": cs.col("high", [r["estimate"] + stats.norm.ppf(1 - (1 - conf) / 2) * r["sd"] for r in cat_rows]),
"term": cs.col("Term", [f"{r['group']}: {r['effect']}" for r in cat_rows], kind="categorical")}),
cs.chart("residuals", "residual-panel", "Residual diagnostics", {"fitted": cs.col("Fitted", fit.fitted), "residual": cs.col("Residual", resid)}),
]
if slopes_tab:
charts.append(cs.chart("coef", "forest", "Fixed effects", {
"label": cs.col("Term", [c["term"] for c in slopes_tab], kind="categorical"), "estimate": cs.col("Estimate", [c["estimate"] for c in slopes_tab]),
"low": cs.col("low", [c["ci_low"] for c in slopes_tab]), "high": cs.col("high", [c["ci_high"] for c in slopes_tab])}, controls={"reference": 0}))
tables = [
{"key": "fixed", "title": "Fixed effects", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "df", "label": "df", "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": coefs, "note": "t tests with Satterthwaite degrees of freedom (lmerTest)."},
]
if effects:
tables.append({"key": "effects", "title": "Joint tests of each predictor", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "f", "label": "F", "type": "number"}, {"key": "df1", "label": "num df", "type": "integer"},
{"key": "df2", "label": "den df", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
"rows": effects, "note": "All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest)."})
tables.append({"key": "random", "title": "Random effects", "columns": [
{"key": "group", "label": "Group", "type": "string"}, {"key": "effect", "label": "Effect", "type": "string"},
{"key": "variance", "label": "Variance", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"}, {"key": "cor", "label": "Correlation", "type": "number"}],
"rows": vc_rows})
tables.append({"key": "modes", "title": "Conditional modes of the random effects", "columns": [
{"key": "group", "label": "Group", "type": "string"}, {"key": "effect", "label": "Effect", "type": "string"}, {"key": "level", "label": "Level", "type": "string"},
{"key": "estimate", "label": "Mode", "type": "number"}, {"key": "sd", "label": "Conditional SD", "type": "number"}], "rows": re_rows[:2000]})
statistics = [{"key": "icc", "label": "ICC (adjusted)", "value": icc}, {"key": "r2_marginal", "label": "R² marginal", "value": var_fixed / total},
{"key": "r2_conditional", "label": "R² conditional", "value": (var_fixed + var_random) / total}, {"key": "sigma", "label": "Residual SD", "value": fit.sigma},
{"key": "aic", "label": "AIC", "value": float(aic)}]
if "re_lrt_p" in values:
statistics.append({"key": "re_lrt_p", "label": "Random effects LR test p", "value": values["re_lrt_p"], "format": "p"})
cs.publish({
"method": "mixed.lmm",
"methodVersion": "1.0.1",
"title": "Linear mixed model",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": (f"F({effects[0]['df1']}, {effects[0]['df2']:.2f}) = {effects[0]['f']:.2f}, {cs.fmt_p(effects[0]['p'])}" if effects else ""),
"statistics": statistics,
"tables": tables,
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings + ([f"Satterthwaite: the (θ, σ) Hessian has {satt.n_negative} negative eigenvalue(s) — the model may not have converged."] if satt.n_negative else []),
"notes": [f"{'REML' if reml else 'Maximum likelihood'} fit of lme4's model (twin of lme4's profiled deviance); fixed effects tested with Satterthwaite df (lmerTest)."],
"charts": charts,
"values": values,
})
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
859 weighings of 72 pigs. Pigs vary with a variance of 39.7, around a residual SD of 3.37 kg, which gives an ICC of 0.777.
The caterpillar plot shows each pig's estimated departure with its interval. Pigs whose intervals clear zero differ from the average pig.
Two R² values
PredictPredict first
A mixed model has two R² valuesMarginal and conditional R²Marginal R² counts the fixed effects, and conditional R² counts the fixed and random effects together.. Marginal counts only the fixed effects. Conditional counts the fixed and random effects together. Which is larger?
Reveal
Conditional, always. Here marginal is 0.918 and conditional is 0.982. A big gap says group membership explains a lot that your predictors don't.
Fixed or random?
ReflectDo you care about these specific groups, or are they a sample from a larger set? Sites in a trial are usually a sample, so random. Your company's three factories are the whole set, so fixed, if you want to compare them.
Random effects also need enough groups to estimate a variance: fewer than about 5 is very imprecise, and the card warns you. How many groups do you have, and could you defend calling them a sample?
Check your understanding
CheckpointCheck yourself
A group has , with and . What's its weight on its own mean?
Show the answer
Answer: 0.8
1 / (1 + 1/4) = 0.8. With 1 row it would be 0.5, and with 100 rows about 0.99.
Check yourself
Why not fit one dummy variable per group and skip random effects?
Show the answer
Answer: b
Dummies are no pooling. That's a reasonable choice in some settings, but you can't then estimate the variance between groups or predict a new one.
Check yourself
The estimate of is 0. What does it mean?
Show the answer
Answer: b
That's a singular fit. It's compatible with no spread, or with too little data to detect it. Simplify the model, and report what happened.
Fit yours
In the appChoose an Outcome and your Fixed effects, and put the unit in Grouping factor. Leave Estimation on REML unless you're comparing models with different fixed effects.
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("s1_dietox.csv").rename(columns={"vitamin E": "vitamin"}).dropna()
df["pig"] = df["pig"].astype(str)
fit = smf.mixedlm("weight ~ week + copper + vitamin", df, groups="pig").fit()
print(fit.summary())
# One intercept departure per pig: shrunken toward zero
effects = pd.Series({pig: re.iloc[0] for pig, re in fit.random_effects.items()})
print(effects.sort_values().head())library(lme4)
df <- read.csv("s1_dietox.csv", check.names = FALSE)
names(df)[names(df) == "vitamin E"] <- "vitamin"
fit <- lmer(weight ~ week + copper + vitamin + (1 | pig), data = df)
summary(fit)
VarCorr(fit)
# One intercept departure per pig: shrunken toward zero
head(sort(ranef(fit)$pig[, 1]))Recap
Recap- Partial pooling blends each group's mean with the overall mean.
- Small groups shrink most, and the data set the amount through .
- Fixed effects are averages, and random effects are departures described by a variance.
- Marginal counts fixed effects. Conditional counts the groups too.
Concepts in this lesson