R lme4 绘制 lmer 残差〜由 ggplot 中的因子水平拟合

R lme4 Plot lmer residuals ~ fitted by Factors levels in ggplot

我想在 ggplot2 中重现 lmer 诊断图。特别是,我知道对于 lmer 模型 DV ~ Factor1 * Factor2 + (1|SubjID) 我可以简单地调用 plot(model, resid(.)~fitted(.)|Factor1+Factor2) 来生成基于格的残差 Vs。拟合图,每个 Factor1+Factor 2 组合的分面图。

我想生成相同的图,但使用的是 ggplot2。我尝试使用 qplot(resid(model), fitted(model)) 和它的不同变体以及不同的参数,但是关于分面所需的因素的信息并没有通过这个(和类似的)调用。

如有任何建议,我将不胜感激,谢谢!

编辑 我的问题的核心:给定任何 lmer 模型,我如何创建一个数据框,包括拟合值和残差值以及每个值的因子信息?类似于:

Factor1 Factor2 Fitted Resid 0 0 987 654 0 0 123 456 (...) 我无法从关于 resid()fitted() 函数

的 lmer 文档中看出这一点

这是我们想要的示例,一个可重现的示例

data(Orthodont, package="nlme")
Orthodont$age <- as.factor(Orthodont$age)

model <- lmer(distance ~ age * Sex + (1|Subject), Orthodont)
plot(model, resid(.) ~ fitted(.) | age + Sex )

回答

ggplot(model, aes(.fitted, .resid)) + geom_point() +
  facet_wrap(~ Sex + age, ncol = 4)    # (edited) I noticed fortify(model) isn't necessary.