首页 > 解决方案 > 如何从 modelsummary 包中的 msummary 的 lmer() 模型中提取拟合优度统计信息

问题描述

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

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

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

我想在生成的回归表中包含观察总数、受试者数量、总 R^2 和固定效应的 R^2 modelsummary()

在此处输入图像描述

我试图提取这些并按照包作者的gof_map 描述构建一个,但没有成功。下面是我的模型输出从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

标签: rregressionlme4lmertestmodelsummary

解决方案


glance问题是默认情况下您的一个统计信息在or中不可用performance,这意味着您需要做一些工作来自定义输出。

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

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

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

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)统计信息,因此我们需要手动添加它。以可复制的方式执行此操作的一种方法是利用文档glance_custom中描述的机制。为此,我们需要知道模型的类是什么:modelsummary

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

然后,我们需要为这个类名定义一个方法。应该调用这个方法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)
模型 1
(截距) 24.708
(3.132)
生命值 -0.030
(0.015)
ñ 32
N(科目) 3
R2(有条件的) 1
R2(边际) 0
AIC 181.895

推荐阅读