r - 如何从 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
解决方案
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 |
推荐阅读
- angularjs - 在两台服务器中启用 cors 过滤器
- c - C 宏在另一个 C 宏中展开
- php - 如何从数据库中删除多条记录(使用 laravel 5.5)
- twitter-bootstrap - bootstrap 4 折叠 data-parent dosent 关闭其他选项卡
- vba - 宏“另存为”并且不打开保存的文档
- fiware - 验证令牌时出错。代理未在 keystone 中授权。梯形验证
- c - string.h 和 stdlib.h 函数给了我错误: undefined reference to '...'
- c - 计数器值小于访问次数的网页计数器
- ffmpeg - ffplay可以看字幕吗
- bash - Bash:如何查找本周修改的文件