A linear mixed effects model is traditionally formulated in the following way. Ri = Xi × β + Zi × bi + εi where β represents estimated fixed effects and Z represents the random effects. X is thus the classical design matrix. Using R, I would like to be able to extract these two matrices after fitting a model using lme from the nlme package. For example, the dataset "Rails", also found in the nlme package, contains three separate measurements of ultrasonic travel time on 6 randomly selected railway rails. I can fit a simple model with an intercept fixed effect and a random effect for each rail with the following.
library(nlme)
lmemodel<-lme(travel ~ 1, random = ~ 1 | Rail, data=Rail)
The X design matrix is just an 18x1 matrix (6 rails * 3 measurements) of unity and is easily extracted in the following way:
model.matrix(lmemodel, data=Rail)
(Intercept)
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
10 1
11 1
12 1
13 1
14 1
15 1
16 1
17 1
18 1
attr(,"assign")
[1] 0
What I would like to do is extract the random effects design matrix Z. I realize if I fit the the same model using the lme4 package, this can be done in the following way:
library(lme4)
lmermodel<-lmer(travel ~ 1 + (1|Rail),data=Rail)
t(lmermodel@Zt) ##takes the transpose of lmermodel@Zt
lmermodel@X ## extracts the X matrix
However, I am at a loss as to how to extract this matrix from an lme fitted model.
getME(lmermodel,"Z")
orgetME(lmermodel,"X")
rather than directly accessing slots in the object, in case the internal representation changes in the future. – Ben Bolker