我之前在这里得到了很好的帮助经验,现在又希望能得到一些帮助。
我正在估计一个相当大的混合效应模型,其中一个随机效应有超过150个不同的水平。这将使得标准的毛虫图变得难以阅读。
如果可能的话,我想要一个毛虫图,只显示随机效应中“显著”的水平(缺乏更好的术语)。也就是说:我需要一个毛虫图,其中随机拦截或变化系数的随机斜率具有不包括零的“置信区间”(我知道这不完全正确)。
考虑这个标准模型来自lme4
的sleepstudy
数据。
library(lme4)
fit <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy)
ggCaterpillar(ranef(fit,condVar=TRUE), QQ=FALSE, likeDotplot=TRUE, reorder=FALSE)[["Subject"]]
我想要得到这个毛毛虫图。
我所使用的毛毛虫图来自于这段代码。请注意,我倾向于使用较少保守的间隔范围(即1.645 * se而不是1.96 * se)。
基本上,我想要一个毛毛虫图,其中只包括308、309、310、330、331、335、337、349、350、352和370这些水平,因为这些水平要么具有截距,要么具有斜率,其区间不包括零。我这样做是因为我的毛毛虫图包含了150多个不同的水平,有点难以阅读,我认为这可能是一个有价值的解决方案。
下面是可重现的代码。非常感谢您的帮助。
# https://dev59.com/EJHea4cB1Zd3GeqPt8gN
ggCaterpillar <- function(re, QQ=TRUE, likeDotplot=TRUE, reorder=TRUE) {
require(ggplot2)
f <- function(x) {
pv <- attr(x, "postVar")
cols <- 1:(dim(pv)[1])
se <- unlist(lapply(cols, function(i) sqrt(pv[i, i, ])))
if (reorder) {
ord <- unlist(lapply(x, order)) + rep((0:(ncol(x) - 1)) * nrow(x), each=nrow(x))
pDf <- data.frame(y=unlist(x)[ord],
ci=1.645*se[ord],
nQQ=rep(qnorm(ppoints(nrow(x))), ncol(x)),
ID=factor(rep(rownames(x), ncol(x))[ord], levels=rownames(x)[ord]),
ind=gl(ncol(x), nrow(x), labels=names(x)))
} else {
pDf <- data.frame(y=unlist(x),
ci=1.645*se,
nQQ=rep(qnorm(ppoints(nrow(x))), ncol(x)),
ID=factor(rep(rownames(x), ncol(x)), levels=rownames(x)),
ind=gl(ncol(x), nrow(x), labels=names(x)))
}
if(QQ) { ## normal QQ-plot
p <- ggplot(pDf, aes(nQQ, y))
p <- p + facet_wrap(~ ind, scales="free")
p <- p + xlab("Standard normal quantiles") + ylab("Random effect quantiles")
} else { ## caterpillar dotplot
p <- ggplot(pDf, aes(ID, y)) + coord_flip()
if(likeDotplot) { ## imitate dotplot() -> same scales for random effects
p <- p + facet_wrap(~ ind)
} else { ## different scales for random effects
p <- p + facet_grid(ind ~ ., scales="free_y")
}
p <- p + xlab("Levels of the Random Effect") + ylab("Random Effect")
}
p <- p + theme(legend.position="none")
p <- p + geom_hline(yintercept=0)
p <- p + geom_errorbar(aes(ymin=y-ci, ymax=y+ci), width=0, colour="black")
p <- p + geom_point(aes(size=1.2), colour="blue")
return(p)
}
lapply(re, f)
}
library(lme4)
fit <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy)
ggCaterpillar(ranef(fit,condVar=TRUE), QQ=FALSE, likeDotplot=TRUE, reorder=FALSE)[["Subject"]]
ggsave(file="sleepstudy.png")
lme4
留言板,知道在随机效应的背景下严肃使用“置信区间”和“显著性”是不合适的。 :P这是一个很好的答案。我之前也不知道broom
包。再次感谢! - steve