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.
What runs in CodeSplash
- Linear mixed model (random intercepts and slopes) Verified in Python and R
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
Not everyone reacts the same
ReadIn 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:
The average slope is still your fixed effect. The spread of says how much people differ from it.
How much data backs the slope?
PredictPredict 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?
Reveal
About 17: (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.
Read the card
In the appF(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
View data
| Conditional mode | Level | high | low | Term |
|---|---|---|---|---|
| −0.0780 | 308 | 24.062 | −24.218 | Subject: (Intercept) |
| −39.831 | 309 | −16.174 | −63.489 | Subject: (Intercept) |
| −38.468 | 310 | −14.811 | −62.125 | Subject: (Intercept) |
| 24.163 | 330 | 47.820 | 0.5054 | Subject: (Intercept) |
| 23.507 | 331 | 47.204 | −0.1901 | Subject: (Intercept) |
| 9.405 | 332 | 33.062 | −14.252 | Subject: (Intercept) |
| 17.204 | 333 | 40.862 | −6.453 | Subject: (Intercept) |
| −6.898 | 334 | 16.760 | −30.555 | Subject: (Intercept) |
| 0.2811 | 335 | 23.938 | −23.376 | Subject: (Intercept) |
| 35.043 | 337 | 58.700 | 11.386 | Subject: (Intercept) |
| −24.876 | 349 | −1.219 | −48.533 | Subject: (Intercept) |
| −12.866 | 350 | 10.791 | −36.523 | Subject: (Intercept) |
| 5.009 | 351 | 28.666 | −18.648 | Subject: (Intercept) |
| 16.324 | 352 | 41.434 | −8.787 | Subject: (Intercept) |
| 3.614 | 369 | 27.272 | −20.043 | Subject: (Intercept) |
| −25.365 | 370 | −1.708 | −49.023 | Subject: (Intercept) |
| 1.190 | 371 | 24.847 | −22.467 | Subject: (Intercept) |
| 12.643 | 372 | 36.300 | −11.014 | Subject: (Intercept) |
| 9.191 | 308 | 13.712 | 4.669 | Subject: Days |
| −8.707 | 309 | −4.185 | −13.228 | Subject: Days |
| −5.522 | 310 | −1.001 | −10.043 | Subject: Days |
| −4.897 | 330 | −0.3761 | −9.419 | Subject: Days |
| −2.636 | 331 | 1.965 | −7.237 | Subject: Days |
| −0.3322 | 332 | 4.189 | −4.853 | Subject: Days |
| −0.2850 | 333 | 4.236 | −4.806 | Subject: Days |
| 1.024 | 334 | 5.545 | −3.497 | Subject: Days |
| −10.857 | 335 | −6.335 | −15.378 | Subject: Days |
| 8.602 | 337 | 13.124 | 4.081 | Subject: Days |
| 1.127 | 349 | 5.648 | −3.395 | Subject: Days |
| 6.589 | 350 | 11.110 | 2.068 | Subject: Days |
| −3.087 | 351 | 1.435 | −7.608 | Subject: Days |
| 3.999 | 352 | 8.607 | −0.6089 | Subject: Days |
| 0.8184 | 369 | 5.340 | −3.703 | Subject: Days |
| 4.792 | 370 | 9.313 | 0.2707 | Subject: Days |
| −1.050 | 371 | 3.472 | −5.571 | Subject: Days |
| 1.230 | 372 | 5.751 | −3.291 | Subject: Days |
View data
| Fitted | Residual |
|---|---|
| 250.77 | −1.206 |
| 270.52 | −11.812 |
| 290.27 | −39.467 |
| 310.02 | 11.421 |
| 349.52 | 65.170 |
| 369.27 | 12.933 |
| 389.02 | −98.873 |
| 408.77 | 21.813 |
| 428.52 | 37.830 |
| 211.01 | 11.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.69 | 9.620 |
| 212.38 | −13.322 |
| 217.41 | −23.082 |
| 222.45 | 11.868 |
| 227.49 | 5.352 |
| 232.53 | −3.220 |
| 237.57 | −17.108 |
| 242.60 | −7.183 |
| 247.64 | 8.109 |
| 252.68 | 8.333 |
| 257.72 | −10.203 |
| 275.01 | 46.536 |
| 280.67 | 19.731 |
| 286.33 | −2.475 |
| 291.99 | −6.862 |
| 297.66 | −11.860 |
| 303.32 | −5.734 |
| 308.98 | −28.743 |
| 314.65 | 3.616 |
| 320.31 | −14.958 |
| 325.97 | 28.078 |
| 274.35 | 13.257 |
| 282.27 | 2.725 |
| 290.20 | 11.622 |
| 298.12 | 21.993 |
| 306.05 | 10.231 |
| 313.97 | −20.651 |
| 329.82 | 5.000 |
| 337.74 | −43.995 |
| 345.67 | 25.916 |
| 260.25 | −25.389 |
| 270.48 | −27.665 |
| 280.70 | −7.744 |
| 290.93 | 18.836 |
| 301.16 | 16.302 |
| 311.39 | −1.391 |
| 321.62 | 132.55 |
| 331.84 | 14.987 |
| 342.07 | −11.772 |
| 352.30 | −98.435 |
| 268.05 | 15.794 |
| 278.32 | 11.232 |
First 60 of 177 rows.
View data
| Estimate | high | Term | low |
|---|---|---|---|
| 10.560 | 13.835 | Days | 7.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
| Term | B | SE | df | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | 250.84 | 6.798 | 17.070 | 36.901 | < .001 | 236.51 | 265.18 |
| Days | 10.560 | 1.552 | 17.020 | 6.802 | < .001 | 7.285 | 13.835 |
t tests with Satterthwaite degrees of freedom (lmerTest).
Joint tests of each predictor
| Term | F | num df | den df | p |
|---|---|---|---|---|
| Days | 46.270 | 1 | 17.020 | < .001 |
All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest).
Random effects
| Group | Effect | Variance | SD | Correlation |
|---|---|---|---|---|
| Subject | (Intercept) | 603.34 | 24.563 | — |
| Subject | Days | 35.418 | 5.951 | — |
| Subject | (Intercept) ~ Days | — | — | 0.0512 |
| Residual | 652.65 | 25.547 | — |
Conditional modes of the random effects
| Group | Effect | Level | Mode | Conditional SD |
|---|---|---|---|---|
| Subject | (Intercept) | 308 | −0.0780 | 12.317 |
| Subject | (Intercept) | 309 | −39.831 | 12.070 |
| Subject | (Intercept) | 310 | −38.468 | 12.070 |
| Subject | (Intercept) | 330 | 24.163 | 12.070 |
| Subject | (Intercept) | 331 | 23.507 | 12.090 |
| Subject | (Intercept) | 332 | 9.405 | 12.070 |
| Subject | (Intercept) | 333 | 17.204 | 12.070 |
| Subject | (Intercept) | 334 | −6.898 | 12.070 |
| Subject | (Intercept) | 335 | 0.2811 | 12.070 |
| Subject | (Intercept) | 337 | 35.043 | 12.070 |
| Subject | (Intercept) | 349 | −24.876 | 12.070 |
| Subject | (Intercept) | 350 | −12.866 | 12.070 |
| Subject | (Intercept) | 351 | 5.009 | 12.070 |
| Subject | (Intercept) | 352 | 16.324 | 12.812 |
| Subject | (Intercept) | 369 | 3.614 | 12.070 |
| Subject | (Intercept) | 370 | −25.365 | 12.070 |
| Subject | (Intercept) | 371 | 1.190 | 12.070 |
| Subject | (Intercept) | 372 | 12.643 | 12.070 |
| Subject | Days | 308 | 9.191 | 2.307 |
| Subject | Days | 309 | −8.707 | 2.307 |
| Subject | Days | 310 | −5.522 | 2.307 |
| Subject | Days | 330 | −4.897 | 2.307 |
| Subject | Days | 331 | −2.636 | 2.348 |
| Subject | Days | 332 | −0.3322 | 2.307 |
| Subject | Days | 333 | −0.2850 | 2.307 |
| Subject | Days | 334 | 1.024 | 2.307 |
| Subject | Days | 335 | −10.857 | 2.307 |
| Subject | Days | 337 | 8.602 | 2.307 |
| Subject | Days | 349 | 1.127 | 2.307 |
| Subject | Days | 350 | 6.589 | 2.307 |
| Subject | Days | 351 | −3.087 | 2.307 |
| Subject | Days | 352 | 3.999 | 2.351 |
| Subject | Days | 369 | 0.8184 | 2.307 |
| Subject | Days | 370 | 4.792 | 2.307 |
| Subject | Days | 371 | −1.050 | 2.307 |
| Subject | Days | 372 | 1.230 | 2.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
))
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
| Term | B | SE | df | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | 250.84 | 6.798 | 17.070 | 36.901 | < .001 | 236.51 | 265.18 |
| Days | 10.560 | 1.552 | 17.020 | 6.802 | < .001 | 7.285 | 13.835 |
t tests with Satterthwaite degrees of freedom (lmerTest).
Joint tests of each predictor
| Term | F | num df | den df | p |
|---|---|---|---|---|
| Days | 46.270 | 1 | 17.020 | < .001 |
All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest).
Random effects
| Group | Effect | Variance | SD | Correlation |
|---|---|---|---|---|
| Subject | (Intercept) | 603.34 | 24.563 | — |
| Subject | Days | 35.418 | 5.951 | — |
| Subject | (Intercept) ~ Days | — | — | 0.0512 |
| Residual | 652.65 | 25.547 | — |
Conditional modes of the random effects
| Group | Effect | Level | Mode | Conditional SD |
|---|---|---|---|---|
| Subject | (Intercept) | 308 | −0.0780 | 12.317 |
| Subject | (Intercept) | 309 | −39.831 | 12.070 |
| Subject | (Intercept) | 310 | −38.468 | 12.070 |
| Subject | (Intercept) | 330 | 24.163 | 12.070 |
| Subject | (Intercept) | 331 | 23.507 | 12.090 |
| Subject | (Intercept) | 332 | 9.405 | 12.070 |
| Subject | (Intercept) | 333 | 17.204 | 12.070 |
| Subject | (Intercept) | 334 | −6.898 | 12.070 |
| Subject | (Intercept) | 335 | 0.2811 | 12.070 |
| Subject | (Intercept) | 337 | 35.043 | 12.070 |
| Subject | (Intercept) | 349 | −24.876 | 12.070 |
| Subject | (Intercept) | 350 | −12.866 | 12.070 |
| Subject | (Intercept) | 351 | 5.009 | 12.070 |
| Subject | (Intercept) | 352 | 16.324 | 12.812 |
| Subject | (Intercept) | 369 | 3.614 | 12.070 |
| Subject | (Intercept) | 370 | −25.365 | 12.070 |
| Subject | (Intercept) | 371 | 1.190 | 12.070 |
| Subject | (Intercept) | 372 | 12.643 | 12.070 |
| Subject | Days | 308 | 9.191 | 2.307 |
| Subject | Days | 309 | −8.707 | 2.307 |
| Subject | Days | 310 | −5.522 | 2.307 |
| Subject | Days | 330 | −4.897 | 2.307 |
| Subject | Days | 331 | −2.636 | 2.348 |
| Subject | Days | 332 | −0.3322 | 2.307 |
| Subject | Days | 333 | −0.2850 | 2.307 |
| Subject | Days | 334 | 1.024 | 2.307 |
| Subject | Days | 335 | −10.857 | 2.307 |
| Subject | Days | 337 | 8.602 | 2.307 |
| Subject | Days | 349 | 1.127 | 2.307 |
| Subject | Days | 350 | 6.589 | 2.307 |
| Subject | Days | 351 | −3.087 | 2.307 |
| Subject | Days | 352 | 3.999 | 2.351 |
| Subject | Days | 369 | 0.8184 | 2.307 |
| Subject | Days | 370 | 4.792 | 2.307 |
| Subject | Days | 371 | −1.050 | 2.307 |
| Subject | Days | 372 | 1.230 | 2.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 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: (3) = 145.2, p < .001.
What happens if you leave it out?
ReflectWithout 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.
REML or ML?
PredictPredict 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?
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.
When the fit is singular
ReadA 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:
- Make the intercept and slope independent.
- Drop the random slope with the smallest variance.
- 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.
Check your understanding
CheckpointCheck 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.
Fit yours
In the appAdd a numeric predictor to Fixed effects and also to Random slopes. Then read the variance table before the fixed effects.
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 covariancelibrary(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 termsstatsmodels gives a z test on a normal scale rather than Satterthwaite's , so its p-value will differ from the card's.
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