【发布时间】:2016-03-24 12:17:43
【问题描述】:
我以前在这里寻求帮助的经历非常好,我希望能再次获得帮助。
我正在估计一个相当大的混合效应模型,其中一个随机效应具有 150 多个不同的级别。这会使标准的毛毛虫图变得非常难以阅读。
如果可能的话,我想得到一个毛毛虫图,其中只有随机效应的水平,由于缺乏更好的术语,“显着”。那就是:我想要一个毛毛虫图,其中随机截距或变化系数的随机斜率具有不包括零的“置信区间”(我知道这不完全是) .
从与lme4 标准的sleepstudy 数据中考虑这个标准模型。
library(lme4)
fit <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy)
ggCaterpillar(ranef(fit,condVar=TRUE), QQ=FALSE, likeDotplot=TRUE, reorder=FALSE)[["Subject"]]
我会得到这个毛毛虫图。
我使用的毛毛虫情节来自this code。请注意,我倾向于对间隔使用不太保守的界限(即 1.645*se 而不是 1.96*se)。
基本上,我想要一个只包含 308、309、310、330、331、335、337、349、350、352 和 370 级别的毛虫图,因为这些级别要么有截距 要么 间隔不包括零的斜率。我问是因为我的 150 多个不同级别的毛毛虫图有点难以理解,我认为这可能是一个值得解决的问题。
可重现的代码如下。我非常感谢任何帮助。
# https://stackoverflow.com/questions/34120578/how-can-i-sort-random-effects-by-value-of-the-random-effect-not-the-intercept
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")
【问题讨论】: