如何预测merMod对象(lme4)的术语? [英] How to predict terms of merMod objects (lme4)?
本文介绍了如何预测merMod对象(lme4)的术语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于简单的glm
对象,我可以使用predict(fit, type = "terms")
检索具有每个术语的拟合值的矩阵.
For simple glm
objects, I can use predict(fit, type = "terms")
to retrieve a matrix with fitted values for each term.
lmer
的等效项是什么. glmer
合适的型号?据我所知,predict.merMod
函数不支持type = terms
.
What is the equivalent for lmer
resp. glmer
fitted models? As far as I can see, the predict.merMod
function does not support type = terms
.
推荐答案
lmer
的等效项是什么.glmer
合适的型号?
What is the equivalent for
lmer
resp.glmer
fitted models?
我不认为有一个.不过,您可以轻松地制作以下内容之一
I do not think there is one. Though, you can easily make one as follows
#####
# fit model with one terms which is a matrix
library(lme4)
fit <- lmer(Reaction ~ cbind(Days, (Days > 3) * Days) + (Days | Subject),
sleepstudy)
#####
# very similar code to `predict.lm`
pred_terms_merMod <- function(fit, newdata){
tt <- terms(fit)
beta <- fixef(fit)
mm <- model.matrix(tt, newdata)
aa <- attr(mm, "assign")
ll <- attr(tt, "term.labels")
hasintercept <- attr(tt, "intercept") > 0L
if (hasintercept)
ll <- c("(Intercept)", ll)
aaa <- factor(aa, labels = ll)
asgn <- split(order(aa), aaa)
if (hasintercept) {
asgn$"(Intercept)" <- NULL
avx <- colMeans(mm)
termsconst <- sum(avx * beta)
}
nterms <- length(asgn)
if (nterms > 0) {
predictor <- matrix(ncol = nterms, nrow = NROW(mm))
dimnames(predictor) <- list(rownames(mm), names(asgn))
if (hasintercept)
mm <- sweep(mm, 2L, avx, check.margin = FALSE)
for (i in seq.int(1L, nterms, length.out = nterms)) {
idx <- asgn[[i]]
predictor[, i] <- mm[, idx, drop = FALSE] %*% beta[idx]
}
} else {
predictor <- ip <- matrix(0, n, 0L)
}
attr(predictor, "constant") <- if (hasintercept) termsconst else 0
predictor
}
# use the function
newdata <- data.frame(Days = c(1, 5), Reaction = c(0, 0))
(out <- pred_terms_merMod(fit, newdata))
#R> cbind(Days, (Days > 3) * Days)
#R> 1 -21.173
#R> 2 21.173
#R> attr(,"constant")
#R> [1] 283.24
#####
# confirm results
beta. <- fixef(fit)
beta.[1] + beta.[2]
#R> (Intercept)
#R> 262.07
out[1] + attr(out, "constant")
#R> [1] 262.07
beta.[1] + (beta.[2] + beta.[3]) * 5
#R> (Intercept)
#R> 304.41
out[2] + attr(out, "constant")
#R> [1] 304.41
据我所知,将上述内容扩展为还包括标准错误应该很简单.
Extending the above to also include standard errors should be straightforward as far as I gather.
这篇关于如何预测merMod对象(lme4)的术语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文