Reputation: 843
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.
Upvotes: 6
Views: 5460
Reputation: 51
model.matrix(formula(lmemodel$modelStruct$reStr)[[1]],data=lmemodel$data)
the 1 is kinda specific to this example because there's only one random effect. When you have multiple random effects, you can do some more automatic programming to stack different Z_i's together.
Upvotes: 5
Reputation: 226182
As far as I can see the Z
matrix isn't stored anywhere in an lme
object. The best bet would be in the modelStruct$reStruct
component (try names(modelfit); str(modelfit); sapply(modelfit,class)
etc. to explore), but it isn't there as far as I can tell. In fact some poking into the guts of lme.default
suggests that the Z
matrix may never actually be explicitly constructed; internally lme
seems to work with grouping structures instead. You can of course do
Z <- model.matrix(~Rail-1,data=Rail)
but that's probably not what you had in mind ...
Upvotes: 2