Skip to content

Random slopes: a line for every person

When an effect differs between people, a random intercept isn't enough. Add a random slope, see why its test has so few degrees of freedom, choose REML or ML, and know what to do with a singular fit.

Advanced ~12 min10 steps

What runs in CodeSplash

You will be able to

  • Say when a predictor needs a random slope
  • Explain why Satterthwaite degrees of freedom track the number of groups
  • Choose REML or ML for the question you're asking
  • Respond to a singular fit by simplifying the model

Read first

01

Not everyone reacts the same

Read

In a sleep-deprivation study, reaction times are measured on successive days in 18 people. Everyone slows down, but some slow much faster than others.

A random intercept lets each person start at a different level. A random slopeRandom slopeLets a predictor's effect differ between groups, around an average slope that remains the fixed effect. lets each person change at a different rate:

yij=(β0+u0j)+(β1+u1j) xij+εijy_{ij} = (\beta_0 + u_{0j}) + (\beta_1 + u_{1j})\,x_{ij} + \varepsilon_{ij}

The average slope β1\beta_1 is still your fixed effect. The spread of u1ju_{1j} says how much people differ from it.

02

How much data backs the slope?

Predict

Predict first

There are 177 rows from 18 people. With random slopes, what do you expect for the denominator degrees of freedom of the test of Days?

About 175About 17About 2
Reveal

About 17: FF(1, 17.0) = 46.3, p < .001. The question is whether the average person's slope differs from zero, and the evidence comes from people. Satterthwaite's methodSatterthwaite degrees of freedomApproximates how many degrees of freedom a mixed-model test really has, which often tracks the number of groups. works out that effective number.

03

Read the card

In the app
Linear mixed modelRecorded · Python and R agreeRecorded 2026-11-17 · 50 values compared · largest relative difference 8.4e-7
R

F(1, 17.02) = 46.27, p < .001

ICC (adjusted)
0.7209
R² marginal
0.2857
R² conditional
0.8007
Residual SD
25.547
AIC
1726.68
Random effects LR test p
< .001

Plots

Random effects (conditional modes)How much do groups differ in a mixed model, and which deviate clearly from the average?
View data
Conditional modeLevelhighlowTerm
−0.078030824.062−24.218Subject: (Intercept)
−39.831309−16.174−63.489Subject: (Intercept)
−38.468310−14.811−62.125Subject: (Intercept)
24.16333047.8200.5054Subject: (Intercept)
23.50733147.204−0.1901Subject: (Intercept)
9.40533233.062−14.252Subject: (Intercept)
17.20433340.862−6.453Subject: (Intercept)
−6.89833416.760−30.555Subject: (Intercept)
0.281133523.938−23.376Subject: (Intercept)
35.04333758.70011.386Subject: (Intercept)
−24.876349−1.219−48.533Subject: (Intercept)
−12.86635010.791−36.523Subject: (Intercept)
5.00935128.666−18.648Subject: (Intercept)
16.32435241.434−8.787Subject: (Intercept)
3.61436927.272−20.043Subject: (Intercept)
−25.365370−1.708−49.023Subject: (Intercept)
1.19037124.847−22.467Subject: (Intercept)
12.64337236.300−11.014Subject: (Intercept)
9.19130813.7124.669Subject: Days
−8.707309−4.185−13.228Subject: Days
−5.522310−1.001−10.043Subject: Days
−4.897330−0.3761−9.419Subject: Days
−2.6363311.965−7.237Subject: Days
−0.33223324.189−4.853Subject: Days
−0.28503334.236−4.806Subject: Days
1.0243345.545−3.497Subject: Days
−10.857335−6.335−15.378Subject: Days
8.60233713.1244.081Subject: Days
1.1273495.648−3.395Subject: Days
6.58935011.1102.068Subject: Days
−3.0873511.435−7.608Subject: Days
3.9993528.607−0.6089Subject: Days
0.81843695.340−3.703Subject: Days
4.7923709.3130.2707Subject: Days
−1.0503713.472−5.571Subject: Days
1.2303725.751−3.291Subject: Days
Residual diagnosticsDo a model's residuals show non-linearity, non-normality, unequal spread or influential points?
View data
FittedResidual
250.77−1.206
270.52−11.812
290.27−39.467
310.0211.421
349.5265.170
369.2712.933
389.02−98.873
408.7721.813
428.5237.830
211.0111.721
212.87−7.600
214.72−11.742
216.57−11.866
218.43−10.711
220.28−4.318
222.13−8.503
223.99−6.260
225.84−1.545
227.699.620
212.38−13.322
217.41−23.082
222.4511.868
227.495.352
232.53−3.220
237.57−17.108
242.60−7.183
247.648.109
252.688.333
257.72−10.203
275.0146.536
280.6719.731
286.33−2.475
291.99−6.862
297.66−11.860
303.32−5.734
308.98−28.743
314.653.616
320.31−14.958
325.9728.078
274.3513.257
282.272.725
290.2011.622
298.1221.993
306.0510.231
313.97−20.651
329.825.000
337.74−43.995
345.6725.916
260.25−25.389
270.48−27.665
280.70−7.744
290.9318.836
301.1616.302
311.39−1.391
321.62132.55
331.8414.987
342.07−11.772
352.30−98.435
268.0515.794
278.3211.232

First 60 of 177 rows.

Fixed effectsHow large are several estimates, how precise, and which exclude the null?
View data
EstimatehighTermlow
10.56013.835Days7.285

Assumptions

  • Normal residuals — Shapiro–Wilk W = 0.898, p < .001 on the conditional residuals.
  • Normal random effects (Subject: (Intercept)) — Shapiro–Wilk W = 0.953, p = .482 on 18 conditional modes.
  • Normal random effects (Subject: Days) — Shapiro–Wilk W = 0.976, p = .896 on 18 conditional modes.
  • Non-singular fit — Every variance component is clearly above zero.
  • Enough groups — 18 levels of Subject.

Fixed effects

TermBSEdftp95% CI low95% CI high
(Intercept)250.846.79817.07036.901< .001236.51265.18
Days10.5601.55217.0206.802< .0017.28513.835

t tests with Satterthwaite degrees of freedom (lmerTest).

Joint tests of each predictor

TermFnum dfden dfp
Days46.270117.020< .001

All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest).

Random effects

GroupEffectVarianceSDCorrelation
Subject(Intercept)603.3424.563—
SubjectDays35.4185.951—
Subject(Intercept) ~ Days——0.0512
Residual652.6525.547—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
Subject(Intercept)308−0.078012.317
Subject(Intercept)309−39.83112.070
Subject(Intercept)310−38.46812.070
Subject(Intercept)33024.16312.070
Subject(Intercept)33123.50712.090
Subject(Intercept)3329.40512.070
Subject(Intercept)33317.20412.070
Subject(Intercept)334−6.89812.070
Subject(Intercept)3350.281112.070
Subject(Intercept)33735.04312.070
Subject(Intercept)349−24.87612.070
Subject(Intercept)350−12.86612.070
Subject(Intercept)3515.00912.070
Subject(Intercept)35216.32412.812
Subject(Intercept)3693.61412.070
Subject(Intercept)370−25.36512.070
Subject(Intercept)3711.19012.070
Subject(Intercept)37212.64312.070
SubjectDays3089.1912.307
SubjectDays309−8.7072.307
SubjectDays310−5.5222.307
SubjectDays330−4.8972.307
SubjectDays331−2.6362.348
SubjectDays332−0.33222.307
SubjectDays333−0.28502.307
SubjectDays3341.0242.307
SubjectDays335−10.8572.307
SubjectDays3378.6022.307
SubjectDays3491.1272.307
SubjectDays3506.5892.307
SubjectDays351−3.0872.307
SubjectDays3523.9992.351
SubjectDays3690.81842.307
SubjectDays3704.7922.307
SubjectDays371−1.0502.307
SubjectDays3721.2302.307
  • 3 of 180 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 df216cc2dfefa65c
# Dataset: s1_sleep (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_sleep.parquet", col_select = c("Reaction", "Days", "Subject")))
n_input <- nrow(df)
df[["Subject"]] <- factor(df[["Subject"]], levels = c("308", "309", "310", "330", "331", "332", "333", "334", "335", "337", "349", "350", "351", "352", "369", "370", "371", "372"))  # stored level order
df <- df[stats::complete.cases(df[c("Reaction", "Days", "Subject")]), , 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("Reaction", "Days", "Subject"))  # infinite values stop the run (registry/errors.yaml)

# %% Model
outcome <- "Reaction"
predictors <- c("Days")
group <- "Subject"
slopes <- c("Days")
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 (TRUE) {
  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
))
Python

F(1, 17.02) = 46.27, p < .001

ICC (adjusted)
0.7209
R² marginal
0.2857
R² conditional
0.8007
Residual SD
25.547
AIC
1726.68
Random effects LR test p
< .001

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

Assumptions

  • Normal residuals — Shapiro–Wilk W = 0.898, p < .001 on the conditional residuals.
  • Normal random effects (Subject: (Intercept)) — Shapiro–Wilk W = 0.953, p = .482 on 18 conditional modes.
  • Normal random effects (Subject: Days) — Shapiro–Wilk W = 0.976, p = .896 on 18 conditional modes.
  • Non-singular fit — Every variance component is clearly above zero.
  • Enough groups — 18 levels of Subject.

Fixed effects

TermBSEdftp95% CI low95% CI high
(Intercept)250.846.79817.07036.901< .001236.51265.18
Days10.5601.55217.0206.802< .0017.28513.835

t tests with Satterthwaite degrees of freedom (lmerTest).

Joint tests of each predictor

TermFnum dfden dfp
Days46.270117.020< .001

All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest).

Random effects

GroupEffectVarianceSDCorrelation
Subject(Intercept)603.3424.563—
SubjectDays35.4185.951—
Subject(Intercept) ~ Days——0.0512
Residual652.6525.547—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
Subject(Intercept)308−0.078012.317
Subject(Intercept)309−39.83112.070
Subject(Intercept)310−38.46812.070
Subject(Intercept)33024.16312.070
Subject(Intercept)33123.50712.090
Subject(Intercept)3329.40512.070
Subject(Intercept)33317.20412.070
Subject(Intercept)334−6.89812.070
Subject(Intercept)3350.281112.070
Subject(Intercept)33735.04312.070
Subject(Intercept)349−24.87612.070
Subject(Intercept)350−12.86612.070
Subject(Intercept)3515.00912.070
Subject(Intercept)35216.32412.812
Subject(Intercept)3693.61412.070
Subject(Intercept)370−25.36512.070
Subject(Intercept)3711.19012.070
Subject(Intercept)37212.64312.070
SubjectDays3089.1912.307
SubjectDays309−8.7072.307
SubjectDays310−5.5222.307
SubjectDays330−4.8972.307
SubjectDays331−2.6362.348
SubjectDays332−0.33222.307
SubjectDays333−0.28502.307
SubjectDays3341.0242.307
SubjectDays335−10.8572.307
SubjectDays3378.6022.307
SubjectDays3491.1272.307
SubjectDays3506.5892.307
SubjectDays351−3.0872.307
SubjectDays3523.9992.351
SubjectDays3690.81842.307
SubjectDays3704.7922.307
SubjectDays371−1.0502.307
SubjectDays3721.2302.307
  • 3 of 180 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 df216cc2dfefa65c
# Dataset: s1_sleep (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_sleep.parquet", columns=["Reaction", "Days", "Subject"])
n_input = len(df)
df["Subject"] = pd.Categorical(df["Subject"], categories=["308", "309", "310", "330", "331", "332", "333", "334", "335", "337", "349", "350", "351", "352", "369", "370", "371", "372"])  # stored level order
df = df.dropna(subset=["Reaction", "Days", "Subject"])  # listwise deletion over the analysis columns
df["Subject"] = df["Subject"].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, ["Reaction", "Days", "Subject"])  # infinite values stop the run (registry/errors.yaml)

# %% Model
outcome = "Reaction"
predictors = ["Days"]
group = "Subject"
slopes = ["Days"]
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 True:
    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,
})

Look at the variance table, which has a row for each random effect and their correlation. The caterpillar plot now has two panels, one for intercepts and one for slopes.

Marginal R2R^2 is 0.286 and conditional is 0.801: most of what the model explains comes from differences between people.

A likelihood-ratio test compares this model with one that has no random effects: χ2\chi^2(3) = 145.2, p < .001.

04

What happens if you leave it out?

Reflect

Without a random slope, the model says everyone shares one slope. So all the disagreement between people has nowhere to go but the residual, and the test of Days now counts each row's slope information as independent.

Why would that make the standard error too small? Run both versions with the handoff below and compare the degrees of freedom.

05

Correlated or independent?

Read

Random intercepts and slopes can be correlated or independent. Correlated is the usual choice: people who start slow may also decline faster.

Independent drops one parameter. It often helps a model that struggles to converge, and it isn't invariant to where you center xx, so center it at a meaningful point if you use it.

Linear mixed modelRecorded · Python and R agreeRecorded 2026-11-17 · 71 values compared · largest relative difference 2.6e-7
R

F(1, 17.08) = 16.57, p < .001

ICC (adjusted)
0.7208
R² marginal
0.3037
R² conditional
0.8056
Residual SD
25.535
AIC
1716.41
Random effects LR test p
< .001

Plots

Random effects (conditional modes)How much do groups differ in a mixed model, and which deviate clearly from the average?
View data
Conditional modeLevelhighlowTerm
0.722230821.381−19.937Subject: (Intercept)
−41.917309−21.680−62.153Subject: (Intercept)
−37.971310−17.735−58.208Subject: (Intercept)
23.84633044.0833.609Subject: (Intercept)
25.75033146.0185.481Subject: (Intercept)
8.35933228.595−11.878Subject: (Intercept)
19.12633339.363−1.111Subject: (Intercept)
−8.53233411.704−28.769Subject: (Intercept)
2.30133522.537−17.936Subject: (Intercept)
34.26733754.50414.030Subject: (Intercept)
−24.349349−4.112−44.586Subject: (Intercept)
−15.0163505.221−35.252Subject: (Intercept)
6.71635126.953−13.520Subject: (Intercept)
15.18635236.713−6.342Subject: (Intercept)
5.04736925.284−15.189Subject: (Intercept)
−27.798370−7.562−48.035Subject: (Intercept)
2.65837122.895−17.578Subject: (Intercept)
11.60537231.842−8.632Subject: (Intercept)
10.65030814.5016.799Subject: Days
−9.946309−6.095−13.797Subject: Days
−3.994310−0.1427−7.845Subject: Days
−6.446330−2.595−10.297Subject: Days
−1.4233312.494−5.341Subject: Days
−1.7583322.093−5.610Subject: Days
0.99273334.844−2.858Subject: Days
−0.30213343.549−4.153Subject: Days
−9.587335−5.735−13.438Subject: Days
7.12233710.9733.271Subject: Days
2.6443496.495−1.207Subject: Days
5.3473509.1981.496Subject: Days
−1.7693512.082−5.620Subject: Days
2.5823526.513−1.350Subject: Days
2.1803696.031−1.672Subject: Days
3.6013707.452−0.2505Subject: Days
0.30703714.158−3.544Subject: Days
−0.19883723.652−4.050Subject: Days
Residual diagnosticsDo a model's residuals show non-linearity, non-normality, unequal spread or influential points?
View data
FittedResidual
251.10−1.543
270.71−12.004
290.31−39.514
309.9211.519
349.1365.557
368.7413.464
388.35−98.197
407.9522.633
427.5638.795
209.3813.356
211.60−6.330
213.81−10.836
216.03−11.325
218.25−10.534
220.47−4.506
222.69−9.056
224.90−7.177
227.12−2.826
229.347.974
212.41−13.355
217.37−23.039
222.3311.987
227.305.546
232.26−2.950
237.22−16.762
242.18−6.762
247.148.607
252.118.906
257.07−9.554
275.1446.402
280.8619.541
286.58−2.721
292.30−7.163
298.01−12.218
303.73−6.148
309.45−29.212
315.173.091
320.89−15.539
326.6127.441
276.1311.478
283.661.338
291.2010.626
298.7321.388
306.2610.017
313.79−20.474
328.865.960
336.39−42.644
343.9227.658
259.65−24.793
270.06−27.248
280.47−7.504
290.8718.898
301.2816.186
311.68−1.685
322.09132.07
332.4914.338
342.90−12.599
353.30−99.441
269.5114.336
279.4610.100

First 60 of 177 rows.

Fixed effectsHow large are several estimates, how precise, and which exclude the null?
View data
EstimatehighTermlow
8.95612.782Days5.130
0.914525.378sleep group: B−23.549
3.2088.620Days × sleep group: B−2.204

Assumptions

  • Normal residuals — Shapiro–Wilk W = 0.897, p < .001 on the conditional residuals.
  • Normal random effects (Subject: (Intercept)) — Shapiro–Wilk W = 0.951, p = .436 on 18 conditional modes.
  • Normal random effects (Subject: Days) — Shapiro–Wilk W = 0.972, p = .833 on 18 conditional modes.
  • Non-singular fit — Every variance component is clearly above zero.
  • Enough groups — 18 levels of Subject.

Fixed effects

TermBSEdftp90% CI low90% CI high
(Intercept)250.389.93917.06925.192< .001233.09267.67
Days8.9562.20017.0794.071< .0015.13012.782
sleep group: B0.914514.06917.1300.0650.949−23.54925.378
Days × sleep group: B3.2083.11217.0971.031.317−2.2048.620

t tests with Satterthwaite degrees of freedom (lmerTest).

Joint tests of each predictor

TermFnum dfden dfp
Days16.573117.079< .001
sleep group0.0042117.130.949
Days × sleep group1.063117.097.317

All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest).

Random effects

GroupEffectVarianceSDCorrelation
Subject(Intercept)662.4325.738—
SubjectDays35.6245.969—
Residual652.0625.535—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
Subject(Intercept)3080.722212.560
Subject(Intercept)309−41.91712.303
Subject(Intercept)310−37.97112.303
Subject(Intercept)33023.84612.303
Subject(Intercept)33125.75012.323
Subject(Intercept)3328.35912.303
Subject(Intercept)33319.12612.303
Subject(Intercept)334−8.53212.303
Subject(Intercept)3352.30112.303
Subject(Intercept)33734.26712.303
Subject(Intercept)349−24.34912.303
Subject(Intercept)350−15.01612.303
Subject(Intercept)3516.71612.303
Subject(Intercept)35215.18613.088
Subject(Intercept)3695.04712.303
Subject(Intercept)370−27.79812.303
Subject(Intercept)3712.65812.303
Subject(Intercept)37211.60512.303
SubjectDays30810.6502.341
SubjectDays309−9.9462.341
SubjectDays310−3.9942.341
SubjectDays330−6.4462.341
SubjectDays331−1.4232.382
SubjectDays332−1.7582.341
SubjectDays3330.99272.341
SubjectDays334−0.30212.341
SubjectDays335−9.5872.341
SubjectDays3377.1222.341
SubjectDays3492.6442.341
SubjectDays3505.3472.341
SubjectDays351−1.7692.341
SubjectDays3522.5822.390
SubjectDays3692.1802.341
SubjectDays3703.6012.341
SubjectDays3710.30702.341
SubjectDays372−0.19882.341
  • 3 of 180 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 6446fd89a3d6f746
# Dataset: s1_sleep (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_sleep.parquet", col_select = c("Reaction", "Days", "sleep group", "Subject")))
n_input <- nrow(df)
df[["sleep group"]] <- factor(df[["sleep group"]], levels = c("A", "B"))  # stored level order
df[["Subject"]] <- factor(df[["Subject"]], levels = c("308", "309", "310", "330", "331", "332", "333", "334", "335", "337", "349", "350", "351", "352", "369", "370", "371", "372"))  # stored level order
df <- df[stats::complete.cases(df[c("Reaction", "Days", "sleep group", "Subject")]), , 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("Reaction", "Days", "sleep group", "Subject"))  # infinite values stop the run (registry/errors.yaml)

# %% Model
outcome <- "Reaction"
predictors <- c("Days", "sleep group")
group <- "Subject"
slopes <- c("Days")
group2 <- NULL
nesting <- "nested"  # nested: (1 | group/group2); crossed: (1 | group2)
correlated <- "independent" == "correlated"  # (1 + x | g) vs (1 + x || g)
interactions <- "first-two"
reml <- "reml" == "reml"
conf <- 0.9
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 (TRUE) {
  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
))
Python

F(1, 17.08) = 16.57, p < .001

ICC (adjusted)
0.7208
R² marginal
0.3037
R² conditional
0.8056
Residual SD
25.535
AIC
1716.41
Random effects LR test p
< .001

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

Assumptions

  • Normal residuals — Shapiro–Wilk W = 0.897, p < .001 on the conditional residuals.
  • Normal random effects (Subject: (Intercept)) — Shapiro–Wilk W = 0.951, p = .436 on 18 conditional modes.
  • Normal random effects (Subject: Days) — Shapiro–Wilk W = 0.972, p = .833 on 18 conditional modes.
  • Non-singular fit — Every variance component is clearly above zero.
  • Enough groups — 18 levels of Subject.

Fixed effects

TermBSEdftp90% CI low90% CI high
(Intercept)250.389.93917.06925.192< .001233.09267.67
Days8.9562.20017.0794.071< .0015.13012.782
sleep group: B0.914514.06917.1300.0650.949−23.54925.378
Days × sleep group: B3.2083.11217.0971.031.317−2.2048.620

t tests with Satterthwaite degrees of freedom (lmerTest).

Joint tests of each predictor

TermFnum dfden dfp
Days16.573117.079< .001
sleep group0.0042117.130.949
Days × sleep group1.063117.097.317

All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest).

Random effects

GroupEffectVarianceSDCorrelation
Subject(Intercept)662.4325.738—
SubjectDays35.6245.969—
Residual652.0625.535—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
Subject(Intercept)3080.722212.560
Subject(Intercept)309−41.91712.303
Subject(Intercept)310−37.97112.303
Subject(Intercept)33023.84612.303
Subject(Intercept)33125.75012.323
Subject(Intercept)3328.35912.303
Subject(Intercept)33319.12612.303
Subject(Intercept)334−8.53212.303
Subject(Intercept)3352.30112.303
Subject(Intercept)33734.26712.303
Subject(Intercept)349−24.34912.303
Subject(Intercept)350−15.01612.303
Subject(Intercept)3516.71612.303
Subject(Intercept)35215.18613.088
Subject(Intercept)3695.04712.303
Subject(Intercept)370−27.79812.303
Subject(Intercept)3712.65812.303
Subject(Intercept)37211.60512.303
SubjectDays30810.6502.341
SubjectDays309−9.9462.341
SubjectDays310−3.9942.341
SubjectDays330−6.4462.341
SubjectDays331−1.4232.382
SubjectDays332−1.7582.341
SubjectDays3330.99272.341
SubjectDays334−0.30212.341
SubjectDays335−9.5872.341
SubjectDays3377.1222.341
SubjectDays3492.6442.341
SubjectDays3505.3472.341
SubjectDays351−1.7692.341
SubjectDays3522.5822.390
SubjectDays3692.1802.341
SubjectDays3703.6012.341
SubjectDays3710.30702.341
SubjectDays372−0.19882.341
  • 3 of 180 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 6446fd89a3d6f746
# Dataset: s1_sleep (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_sleep.parquet", columns=["Reaction", "Days", "sleep group", "Subject"])
n_input = len(df)
df["sleep group"] = pd.Categorical(df["sleep group"], categories=["A", "B"])  # stored level order
df["Subject"] = pd.Categorical(df["Subject"], categories=["308", "309", "310", "330", "331", "332", "333", "334", "335", "337", "349", "350", "351", "352", "369", "370", "371", "372"])  # stored level order
df = df.dropna(subset=["Reaction", "Days", "sleep group", "Subject"])  # listwise deletion over the analysis columns
df["sleep group"] = df["sleep group"].cat.remove_unused_categories()
df["Subject"] = df["Subject"].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, ["Reaction", "Days", "sleep group", "Subject"])  # infinite values stop the run (registry/errors.yaml)

# %% Model
outcome = "Reaction"
predictors = ["Days", "sleep group"]
group = "Subject"
slopes = ["Days"]
group2 = None
nesting = "nested"  # nested: (1 | group/group2); crossed: (1 | group2)
correlated = "independent" == "correlated"  # (1 + x | g) vs (1 + x || g)
interactions = "first-two"
reml = "reml" == "reml"
conf = 0.9
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 True:
    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,
})

This version also lets the two sleep groups have different slopes. It has 2 variance parameters, against 3 above.

06

REML or ML?

Predict

Predict first

You want to compare a model with Days against one without it, using a likelihood-ratio test. Which estimation should you use for both?

REMLMLEither
Reveal

ML. REMLREMLThe default way to estimate variance components in mixed models; less biased than ML for small samples. removes the fixed effects before it estimates the variances, so REML likelihoods from different fixed effects aren't comparable. Use REML for your final estimates, because it corrects ML's downward bias in the variances, and ML when fixed effects differ between the models you're comparing.

07

When the fit is singular

Read

A singular fitSingular fitA mixed model estimated a variance of zero or a perfect correlation; the random-effects structure is too rich for the data. means a variance was estimated at zero, or a correlation at ±1. The model is asking for more structure than the data can support. This fit isn't singular, and the card would warn you if it were.

Respond by simplifying, one step at a time:

  1. Make the intercept and slope independent.
  2. Drop the random slope with the smallest variance.
  3. Report what you removed, and why.

Don't delete it silently. With few groups, a slope's variance can look like zero even when real differences exist.

08

Check your understanding

Checkpoint

Check yourself

Students are tested before and after a course, in 40 schools. Which term do you need if the course's effect may differ between schools?

Show the answer

Answer: b

Only a random slope lets the effect vary between schools. Without it, the test of the course is too optimistic if schools do differ.

Check yourself

A random-slope model has 5,000 rows from 25 sites. The test of the slope reports about 24 denominator df. What does that show?

Show the answer

Answer: b

Rows sharpen each site's slope, but the average slope generalizes across sites. More sites help far more than more rows.

Check yourself

The card reports a singular fit: the correlation between intercept and slope is −1. What's the best first step?

Show the answer

Answer: a

Simplify the part that's failing. Dropping grouping altogether would bring back the independence problem.

Check yourself

Two models have the same fixed effects, and differ only in their random effects. Which comparison is fine?

Show the answer

Answer: a

REML likelihoods are comparable when fixed effects match. Note that a variance tested against zero sits on a boundary, so the plain χ² p-value tends to be conservative.

09

Fit yours

In the app

Add a numeric predictor to Fixed effects and also to Random slopes. Then read the variance table before the fixed effects.

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

df = pd.read_csv("s1_sleep.csv").dropna()
df["Subject"] = df["Subject"].astype(str)

fit = smf.mixedlm("Reaction ~ Days", df, groups="Subject", re_formula="~Days").fit()
print(fit.summary())
print(fit.cov_re)  # variances of intercepts and slopes, with their covariance
R
library(lmerTest)  # lme4's lmer with Satterthwaite degrees of freedom

df <- read.csv("s1_sleep.csv", check.names = FALSE)

fit <- lmer(Reaction ~ Days + (1 + Days | Subject), data = df)
summary(fit)
anova(fit)
ranova(fit)  # tests the random terms

statsmodels gives a z test on a normal scale rather than Satterthwaite's FF, so its p-value will differ from the card's.

10

Recap

Recap
  • If an effect can differ between groups, give it a random slope.
  • The test of the average slope draws on groups, so its df track the number of groups.
  • Use REML for final estimates and ML to compare different fixed effects.
  • Treat a singular fit as a request to simplify, and report what you did.

Concepts in this lesson