如何从 modelsummary 包中的 msummary 的 lmer() 模型中提取拟合优度统计信息

How to extract the goodness-of-fit statistics from lmer() model for msummary from modelsummary package

我正在使用 lmerTest::lmer() 对重复测量数据执行线性回归。

我的模型包含一个固定效应(具有 5 个水平的因子)和一个随机效应(主题):

library(lmerTest) 
model_lm  <- lmer(likertscore ~ task.f + (1 | subject), data = df_long)  

我想在我用 modelsummary().

我试图提取这些并由包的作者构建一个 gof_map as described 但没有成功。 在 lmerTest::lmer() 的模型输出下方,获得的性能指标:

Linear mixed model fit by REML ['lmerModLmerTest']
Formula: likertscore ~ factor + (1 | subject)
   Data: df_long
REML criterion at convergence: 6674.915
Random effects:
 Groups   Name        Std.Dev.
 subject  (Intercept) 1.076   
 Residual             1.514   
Number of obs: 1715, groups:  subject, 245
Fixed Effects:
                      (Intercept)                         factor1                         factor2  
                           3.8262                             1.5988                             0.3388  
                      factor3                             factor4                         factor5  
                          -0.7224                            -0.1061                            -1.1102  

library("performance")
performance::model_performance(my_model)

# Indices of model performance

AIC     |     BIC | R2 (cond.) | R2 (marg.) |  ICC | RMSE | Sigma
-----------------------------------------------------------------
6692.91 | 6741.94 |       0.46 |       0.18 | 0.34 | 1.42 |  1.51

问题是您的一项统计信息在 glanceperformance 中默认不可用,这意味着您需要做一些工作来自定义输出。

首先,我们加载库并估计模型:

library(modelsummary)
library(lmerTest) 
mod  <- lmer(mpg ~ hp + (1 | cyl), data = mtcars) 

然后,我们使用 modelsummary 包中的 get_gof 函数检查开箱即用的拟合优度统计数据:

get_gof(mod)
#>        aic      bic r2.conditional r2.marginal       icc     rmse    sigma nobs
#> 1 181.8949 187.7578      0.6744743   0.1432201 0.6200592 2.957141 3.149127   32

您会注意到那里没有 N (subject) 统计信息,因此我们需要手动添加它。以可复制的方式执行此操作的一种方法是利用 modelsummary documentation. 中描述的 glance_custom 机制为此,我们需要知道模型的 class 是什么:

class(mod)[1]
#> [1] "lmerModLmerTest"

然后,我们需要为这个class名字定义一个方法。这个方法应该叫做glance_custom.CLASSNAME。在 lmerModLmerTest 模型中,可以通过获取摘要中的 ngrps 对象来检索组数。所以我们这样做:

glance_custom.lmerModLmerTest <- function(x, ...) {
  s <- summary(x)
  out <- data.frame(ngrps = s$ngrps)
  out
}

最后,我们使用 gof_map 参数来格式化结果:

gm <- list(
  list(raw = "nobs", clean = "N", fmt = 0),
  list(raw = "ngrps", clean = "N (subjects)", fmt = 0),
  list(raw = "r2.conditional", clean = "R2 (conditional)", fmt = 0),
  list(raw = "r2.marginal", clean = "R2 (marginal)", fmt = 0),
  list(raw = "aic", clean = "AIC", fmt = 3)
)

modelsummary(mod, gof_map = gm)
Model 1
(Intercept) 24.708
(3.132)
hp -0.030
(0.015)
N 32
N (subjects) 3
R2 (conditional) 1
R2 (marginal) 0
AIC 181.895