How to get covariance matrix for random effects (BLUPs/conditional modes) from lme4

☆樱花仙子☆ 提交于 2019-11-29 07:35:15

From ?ranef:

If ‘condVar’ is ‘TRUE’ each of the data frames has an attribute called ‘"postVar"’ which is a three-dimensional array with symmetric faces; each face contains the variance-covariance matrix for a particular level of the grouping factor. (The name of this attribute is a historical artifact, and may be changed to ‘condVar’ at some point in the future.)

Set up an example:

library(lme4)
fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
rr <- ranef(fm1,condVar=TRUE)

Get the variance-covariance matrix among the b values for the intercept

pv <- attr(rr[[1]],"postVar")
str(pv)
##num [1:2, 1:2, 1:18] 145.71 -21.44 -21.44 5.31 145.71 ...

So this is a 2x2x18 array; each slice is the variance-covariance matrix among the conditional intercept and slope for a particular subject (by definition, the intercepts and slopes for each subject are independent of the intercepts and slopes for all other subjects).

To convert this to a variance-covariance matrix (see getMethod("image",sig="dgTMatrix") ...)

library(Matrix)
vc <- bdiag(  ## make a block-diagonal matrix
            lapply(
                ## split 3d array into a list of sub-matrices
                split(pv,slice.index(pv,3)),
                   ## ... put them back into 2x2 matrices
                      matrix,2)) 
image(vc,sub="",xlab="",ylab="",useRaster=TRUE)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!