如何为 lmer 混合模型绘制效果图?

How can I make effects plots for a lmer mixed model?

我之前已经成功地将 effects 包用于 lmglm 模型。它应该支持 lme4 混合模型,但我无法让它在大多数情况下工作。

有什么建议吗?我在下面有一个可重现的示例,其中包含两个有效的 lmer 模型,这些模型会产生 effects 错误。

是否有用于计算和绘制模型效果的替代包?

library(lme4)
library(effects)

# example from documentation works
fm1 <- lmer(angle ~ recipe * temperature + (1|recipe:replicate), cake,
            REML = FALSE)
print(Effect(c("recipe", "temperature"), fm1))
#> 
#>  recipe*temperature effect
#>       temperature
#> recipe      175      185      195      205      215      225
#>      A 29.13333 31.53333 30.80000 33.53333 38.66667 35.06667
#>      B 26.86667 29.40000 31.73333 32.13333 34.46667 35.26667
#>      C 27.93333 28.93333 31.73333 30.86667 34.40000 35.73333

# this is a valid model with no singularities 
fm2 <- lmer(angle ~ temp + (1 | replicate), cake)
print(fm2)
#> Linear mixed model fit by REML ['lmerMod']
#> Formula: angle ~ temp + (1 | replicate)
#>    Data: cake
#> REML criterion at convergence: 1671.711
#> Random effects:
#>  Groups    Name        Std.Dev.
#>  replicate (Intercept) 6.260   
#>  Residual              4.849   
#> Number of obs: 270, groups:  replicate, 15
#> Fixed Effects:
#> (Intercept)         temp  
#>      0.5159       0.1580

# effects doesn't work
Effect(c("temp", "replicate"), fm2)
#> Error in Analyze.model(focal.predictors, mod, xlevels, default.levels, : the following predictor is not in the model: replicate
Effect(c("replicate"), fm2)
#> Error in Analyze.model(focal.predictors, mod, xlevels, default.levels, : the following predictor is not in the model: replicate
Effect(c("temp"), fm2)
#> 
#>  temp effect
#> temp
#>      180      190      200      210      220 
#> 28.96159 30.54190 32.12222 33.70254 35.28286

# this doesn't work either
my_cake <- cake
my_cake <- within(my_cake, temp <- temp - mean(temp))
fm3 <- lmer(angle ~ (temp || replicate), my_cake)

Effect(c("temp", "replicate"), fm3)
#> Error in Analyze.model(focal.predictors, mod, xlevels, default.levels, : the following predictors are not in the model: temp, replicate
Effect(c("replicate"), fm3)
#> Error in Analyze.model(focal.predictors, mod, xlevels, default.levels, : the following predictor is not in the model: replicate
Effect(c("temp"), fm3)
#> Error in Analyze.model(focal.predictors, mod, xlevels, default.levels, : the following predictor is not in the model: temp

reprex package (v2.0.1)

于 2022-04-22 创建

您的问题是您试图绘制涉及随机项的效应。在您的第一个示例中,您的效果仅涉及 fixed-effect 项。

我能很快得到的最接近的是

cowplot::plot_grid(
   plot(Effect("temp", fm2)),
   lattice::dotplot(ranef(fm2))$replicate
)

library(sjPlot)
cowplot::plot_grid(
   plot_model(fm2, "eff")$temp,
   plot_model(fm2, "re")
)

  • 我认为 emmeanseffects 都不能处理随机效应
  • sjPlot 包有很多不同的功能,但我不认为将随机效应视为 'effects' 是其中之一
  • 请注意,此处显示的重复效应是相对于总体平均值的值,而不是预测值

如图 here 所示,您可以生成最多包含 9 个随机采样级别的预测图,但 (AFAICT) 不可能使用 >9 个级别(因为 hard-coded 限制颜色的数量!)

plot(ggpredict(fm2, terms = c("temp", "replicate [sample = 9]"), type ="random"))