back to the general definition

\[ \begin{split} \underbrace{Y_i}_{\text{response}} & \sim \overbrace{\text{Distr}}^{\substack{\text{conditional} \\ \text{distribution}}}(\underbrace{g^{-1}(\eta_i)}_{\substack{\text{inverse} \\ \text{link} \\ \text{function}}},\underbrace{\phi}_{\substack{\text{scale} \\ \text{parameter}}}) \\ \underbrace{\boldsymbol \eta}_{\substack{\text{linear} \\ \text{predictor}}} & = \underbrace{\boldsymbol X\boldsymbol \beta}_{\substack{\text{fixed} \\ \text{effects}}} + \underbrace{\boldsymbol Z\boldsymbol b}_{\substack{\text{random} \\ \text{effects}}} \\ \underbrace{\boldsymbol b}_{\substack{\text{conditional} \\ \text{modes}}} & \sim \text{MVN}(\boldsymbol 0, \underbrace{\Sigma(\boldsymbol \theta)}_{\substack{\text{variance-} \\ \text{covariance} \\ \text{matrix}}}) \end{split} \]

fixed-effect model matrix

packages

library(Matrix)
library(reformulas)

example

terms(~ mpg * disp, data = mtcars)
model.matrix(hp~ mpg * disp, data = mtcars)

random-effect formulas

from RE formula to model objects: RE model matrix \(\boldsymbol Z\)

f <- factor(rep(1:3, each = 2))
Ji <- t(as(f, "sparseMatrix"))
Xi <- cbind(1, rep.int(c(-1, 1), 3L))
Zi <- t(Matrix::KhatriRao(t(Ji), t(Xi)))

from RE formula to model objects: RE covariance matrix \(\Sigma\)

lme4 example

dd <- expand.grid(f1 = factor(1:3), f2 = factor(1:2), g1 = factor(1:5), g2 = factor(1:6))
dd$y <- 1
form <- y ~ 1 + (f1 | g1) + (f2 | g2)
rt <- reformulas::mkReTrms(
                      bar = findbars(form),
                      fr = model.frame(subbars(form), data = dd))
Sigma <- rt$Lambdat %*% t(rt$Lambdat)
image(Sigma)

references

1.
Wilkinson, G. N. & Rogers, C. E. Symbolic description of factorial models for analysis of variance. Applied Statistics 22, 392–399 (1973).
2.
Chambers, J. M. & Hastie, T. J. Statistical Models. in Statistical Models in S (Routledge, 1992).
3.
Bates, D., Mächler, M., Bolker, B. M. & Walker, S. C. Fitting linear mixed-effects models using lme4. Journal of Statistical Software 67, 1–48 (2015).