我有一个模型,例如:
mymod = lmer(y ~ x1 + x2 + (x1 | id) , data = mydata)
我知道我可以使用getME
从拟合对象中获取模型矩阵,但是有没有办法获取固定效应的模型矩阵而无需先拟合模型 :
最佳答案
您可以使用 lme4 包中的 lformula
函数来完成此操作。这将重新生成一个对象,该对象保存了该矩阵的转置,Zt
:
library(lme4)
# create some toy data
dt <- expand.grid(x1 = 1:4, x2 = 5:6, id = LETTERS[1:20], reps = 1:2)
# this is the model in the OP:
myFormula = "y ~ x1 + x2 + (x1 | id)"
# for lFormula to work we need y in the data frame
# so just put a vector of 1s since that will not affect the random effects model matrix:
dt$y <- 1
然后:
foo <- lFormula(eval(myFormula), dt)
Z <- t(as.matrix(foo$reTrms$Zt))
其中 Z
是您请求的随机效应的模型矩阵。
关于r - 如何获得随机效应模型矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70709438/