I am currently writing a script to evaluate the (limited) log-likelihood function for use in linear mixed models. I need this to calculate the probability of a model with some parameters fixed to arbitrary values. Perhaps this script is also useful for some of you!
I use lmer()from lme4and logLik()to check if my script is working. And, as it seems, this is not so! Since my educational experience was not really related to this level of statistics, I lost a little when I discovered an error.
Below you will find a short example script using sleepstudy data:
library(lme4)
data(sleepstudy)
dat <- sleepstudy[ (sleepstudy$Days %in% 0:4) & (sleepstudy$Subject %in% 331:333) ,]
colnames(dat) <- c("y", "x", "group")
mod0 <- lmer( y ~ 1 + x + ( 1 | group ), data = dat)
q <- nrow(VarCorr(mod0)$group)
n <- nrow(dat)
m <- length(unique(dat$group))
Y <- dat$y
X <- cbind(rep(1,n), dat$x)
beta <- as.numeric(fixef(mod0))
Z.sparse <- t(mod0@Zt)
Z <- as.matrix(Z.sparse)
b <- as.matrix(ranef(mod0)$group)
D <- diag(VarCorr(mod0)$group[1:q,1:q], q*m)
R <- diag(1,nrow(dat))*summary(mod0)@sigma^2
V <- Z %*% D %*% t(Z) + R
Y.test <- X %*% beta + Z %*% b + resid(mod0)
cbind(Y, Y.test)
loglik.p <- - (0.5) * ( (log(det(V))) + t((Y - X %*% beta)) %*% solve(V) %*% (Y - X %*% beta) )
loglik.r <- loglik.p - (0.5) * log(det( t(X) %*% solve(V) %*% X ))
loglik.lmer <- logLik(mod0, REML=TRUE)
cbind(loglik.p, loglik.r, loglik.lmer)
, LMM-, ? !
edit: BTW, LMM (1977), (), :
,