DRegression models · mixed.lmm
Linear mixed model (random intercepts and slopes)
How does a numeric outcome depend on predictors when rows are grouped (repeated measures, clusters)?
lme4-style linear mixed model: fixed effects for numeric and categorical predictors (treatment contrasts, optional pairwise interactions), random intercepts (and slopes, correlated or independent) for a grouping factor, optionally a second grouping factor nested in or crossed with the first; REML or ML. Fixed effects with Satterthwaite degrees of freedom (lmerTest), joint F tests per predictor, variance components with correlations, ICC, Nakagawa's marginal and conditional R², a likelihood-ratio test of the random effects and the conditional modes of the random effects (caterpillar plot).
A real result
Example “Sleep slopes”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
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).
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).
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Sleep slopess1_sleep · group: Subject · outcome: Reaction · predictors: Days · slopes: Days
- Sleep independent factors1_sleep · group: Subject · outcome: Reaction · predictors: Days, sleep group · slopes: Days
- Pastes nesteds1_pastes · group: batch · group2: cask · outcome: strength
- Penicillin crossed mls1_penicillin · group: plate · group2: sample · outcome: diameter
- Dietox factorss1_dietox · group: pig · outcome: weight · predictors: week, copper, vitamin E
- Degenerate constants1_sleep · group: Subject · outcome: Reaction · predictors: Days · slopes: Days
- Degenerate single levels1_sleep · group: Subject · outcome: Reaction · predictors: Days · slopes: Days
- Degenerate huge cardinalitys1_sleep · group: Subject · outcome: Reaction · predictors: Days · slopes: Days
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Study design: independent / paired / repeated / clustered · Statistics Guide · Step 0 — Prepare your data
- More than two repeated measures: RM ANOVA, Friedman · Statistics Guide · B — Compare groups
- Repeated / clustered: mixed models, GEE · Statistics Guide · D — Predict an outcome
- Independence · Statistics Guide · Step 2 — Check assumptions
- Generalized models · Statistics Guide · Step 3 — If assumptions are violated
- Regression (linear, GLM), ANOVA, t-tests, chi-square · DS & ML Decision Guide · Explain — why is it happening?
What you need
- Outcomenumeric · 1 column
- The numeric variable you are analyzing.
- Fixed effectsnumeric / categorical / boolean · 0–20 columns · 2–30 levels
- Predictors whose average effect you want (time, treatment, covariates). Categorical ones enter as dummies against their first level.
- Grouping factorcategorical / numeric / boolean · 1 column
- The unit rows belong to (subject, school, site): each gets its own random intercept.
- Random slopesnumeric · 0–3 columns
- Numeric predictors whose effect may differ between groups (usually also listed as fixed effects).
- Second grouping factorcategorical / numeric / boolean · 0–1 column
- A second level of grouping — nested in the first (classes within schools) or crossed with it (items × raters).
Choices you make
statistics
- Estimationdefault reml
REML estimates variance components without the small-sample bias of ML; use ML to compare models with different fixed effects.
- REML (recommended)(default) — Corrects variance estimates for the fixed effects being estimated; the better choice for variance components.
- Maximum likelihood — Uses the full likelihood; needed to compare models with different fixed effects, though variances run small.
- Second grouping factor isdefault nested
Nested — each level of the second factor belongs to one level of the first (labels may repeat across groups). Crossed — levels combine freely.
- Nested in the first ((1 | g1/g2))(default) — Treats the second group as inside the first, so its labels matter only within it; pick it for pupils in classes in schools.
- Crossed with the first ((1 | g2)) — Treats the second group as separate from the first; pick it for subjects crossed with items.
- Random intercepts and slopesdefault correlated
Whether random intercepts and slopes may correlate (usual), or are kept independent (simpler; can help convergence).
- Correlated ((1 + x | g))(default) — Estimates how random intercepts and slopes move together; the usual choice.
- Independent ((1 + x || g)) — Sets that correlation to zero; pick it when the correlated fit fails to converge or is singular.
- Interactionsdefault none
Add interaction terms so the effect of one predictor can depend on the value of another.
- None (main effects only)(default) — Fits main effects only; the usual starting point and the easiest to read.
- First two predictors (A × B) — Adds the A × B term for the first two predictors; pick it when you expect one effect to depend on the other.
- All pairs of predictors — Adds every two-way term; uses many coefficients, so pick it with plenty of rows and a reason to look.
- Test the random effects (likelihood ratio)default on
Refits the model and a model without random effects by ML; with one variance component the p-value uses the 50:50 χ² mixture (boundary).
hypothesis
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Normal residuals
Normal random effects
Shapiro–Wilk on the conditional modes of each random effect (needs at least 8 groups).
Non-singular fit
A variance estimated at zero (or a correlation of ±1) means the random-effects structure is too complex for the data.
Enough groups
Variance components need several groups; fewer than 5 makes them very imprecise.
What it reports
- Tests: First fixed effect (Satterthwaite F test)
- n
- How many independent units the analysis used; it sets precision and power.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- n_groups
- How many independent units the analysis used; it sets precision and power.
- sigma
- The distance between two distributions' average kernel embeddings; zero when they are equal.
- log_lik
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- deviance
- Twice the gap in log-likelihood between a model and a perfect fit; GLMs' analog of the residual sum of squares.
- aic
- A model score balancing fit against complexity; lower is better, and only differences matter.
- bic
- Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
- icc
- The share of variance due to differences between groups (or raters' agreement on the same subjects).
- r2_marginal
- Marginal R² counts the fixed effects, and conditional R² counts the fixed and random effects together.
- r2_conditional
- Marginal R² counts the fixed effects, and conditional R² counts the fixed and random effects together.
- var_fixed
- Marginal R² counts the fixed effects, and conditional R² counts the fixed and random effects together.
- var_random
- Marginal R² counts the fixed effects, and conditional R² counts the fixed and random effects together.
- singular
- A mixed model estimated a variance of zero or a perfect correlation; the random-effects structure is too rich for the data.
- n_params
- How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.
- n_theta
- How many independent units the analysis used; it sets precision and power.
- max_interaction_order
- The most factors combined in one term of the model: 1 means main effects only, 2 two-way interactions.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
- reml
- The default way to estimate variance components in mixed models; less biased than ML for small samples.
- focal_f
- The ratio of explained to unexplained variance, used by ANOVA and regression tests.
- focal_df1
- How much independent information is left to estimate variability after fitting the model.
- focal_df2
- How much independent information is left to estimate variability after fitting the model.
- focal_p
- How surprising your data would be if the null hypothesis were true, as a probability.
Per group, level or term: coef[<term>], se[…], df[…], t[…], p[…], ci_low[…], ci_high[…], f[<predictor>], f_df1[…], f_df2[…], f_p[…], var[<group>|<effect>], sd[…], cor[<group>|<effect>|<effect>], n_groups2, re_lrt, re_lrt_df, re_lrt_p, sw_p_resid
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, scipy, codesplash; R uses lme4, lmerTest, nanoparquet, codesplashr.
Default traps between the two languages
- Python has no lme4: the Python engine computes the same profiled (RE)ML deviance as lme4 (penalized least squares on the relative covariance factor Λθ) and Satterthwaite degrees of freedom as lmerTest does, from its own Richardson-extrapolated Hessian and Jacobian. Both engines optimize θ to ~1e-10 (R: bobyqa with rhoend = 1e-12), but the deviance is flat to rounding near its optimum, so θ agrees to ~1e-7: fixed effects, standard errors and df to ~1e-7, variance components to ~1e-6, correlations of small components to ~1e-5.
- statsmodels' MixedLM fits one grouping factor (crossed effects only as variance components) and reaches lme4's variance components only to ~1e-4, with no Satterthwaite df, so it is not used.
The exact script CodeSplash ran for example “Sleep slopes” · 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,
})
The exact script CodeSplash ran for example “Sleep slopes” · 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
))
Sources
- Bates, D., Mächler, M., Bolker, B., & Walker, S. (2015). Fitting linear mixed-effects models using lme4. Journal of Statistical Software, 67(1), 1–48.
- Kuznetsova, A., Brockhoff, P. B., & Christensen, R. H. B. (2017). lmerTest package: Tests in linear mixed effects models. Journal of Statistical Software, 82(13).
- Nakagawa, S., Johnson, P. C. D., & Schielzeth, H. (2017). The coefficient of determination R² and intra-class correlation coefficient from generalized linear mixed-effects models revisited and expanded. Journal of the Royal Society Interface, 14, 20170213.
- Johnson, P. C. D. (2014). Extension of Nakagawa & Schielzeth's R²GLMM to random slopes models. Methods in Ecology and Evolution, 5, 944–946.
From the CodeSplash method registry · mixed.lmm v1.0.1.