[R-sig-ME] design matrix for mixed effects model

Douglas Bates bates at stat.wisc.edu
Mon Jan 10 18:30:22 CET 2011

```On Fri, Jan 7, 2011 at 1:51 PM, Wade Wall <wade.wall at gmail.com> wrote:
> Hi all,
>
> Is there a function to recreate the design matrix for mixed models similar
> to the model.matrix function?  I want to be able to calculate the fitted
> values for my own sanity and understanding, but not sure how to add in the
> random effects part of the design matrix.

There is a method for model.matrix for models fit by lmer.  That
returns the model matrix for the fixed-effects parameters.  Right now
the model matrix for the random effects is kind of hidden in the
structure.  In the released version of the lme4 package the transpose
of the random effects model matrix is stored as the Zt slot of the
fitted model object.

> fm1 <- lmer(Yield ~ 1 + (1|Batch), Dyestuff)
> str(model.matrix(fm1))
num [1:30, 1] 1 1 1 1 1 1 1 1 1 1 ...
- attr(*, "assign")= int 0
> str(fm1 at Zt)
Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
..@ i       : int [1:30] 0 0 0 0 0 1 1 1 1 1 ...
..@ p       : int [1:31] 0 1 2 3 4 5 6 7 8 9 ...
..@ Dim     : int [1:2] 6 30
..@ Dimnames:List of 2
.. ..\$ : NULL
.. ..\$ : NULL
..@ x       : num [1:30] 1 1 1 1 1 1 1 1 1 1 ...
..@ factors : list()
> fm1 at Zt
6 x 30 sparse Matrix of class "dgCMatrix"

[1,] 1 1 1 1 1 . . . . . . . . . . . . . . . . . . . . . . . . .
[2,] . . . . . 1 1 1 1 1 . . . . . . . . . . . . . . . . . . . .
[3,] . . . . . . . . . . 1 1 1 1 1 . . . . . . . . . . . . . . .
[4,] . . . . . . . . . . . . . . . 1 1 1 1 1 . . . . . . . . . .
[5,] . . . . . . . . . . . . . . . . . . . . 1 1 1 1 1 . . . . .
[6,] . . . . . . . . . . . . . . . . . . . . . . . . . 1 1 1 1 1

As a result of your question and of looking at the slides for a short
course tomorrow, I think I should add an argument to the model.matrix
method to allow for extracting the model matrix for the random effects
without needing to know the details of the structure.

```