R中modelsummary生成平均偏效应表异常输出与警告处理咨询
多二值响应模型平均偏效应表格生成问题处理
问题描述
需要输出多个二值响应模型的平均偏效应汇总表格:
- 早期版本中,对类为
"margins" "data.frame"的对象列表调用modelsummary函数可正常生成目标表格 - 当前版本中,对
margins或marginaleffects类对象列表调用该函数时,会生成大量重复冗余行,同时返回如下警告:
--- Objects of class 'NULL' are currently not supported. Objects of class 'NULL' are currently not supported. Objects of class 'NULL' are currently not supported. Objects of class 'NULL' are currently not supported. Warning message: There are duplicate term names in the table. The `shape` argument of the `modelsummary` function can be used to print related terms together, and to label them appropriately. You can find the group identifier to use in the `shape` argument by calling `get_estimates()` on one of your models. Candidate group identifiers include: type, contrast. See `?modelsummary` for details.
复现代码
# 复现示例 df <- mtcars df$cyl <- as.factor(df$cyl) library(modelsummary) library(tidyverse) library(marginaleffects) # 拟合二值响应模型 model1 <- glm(am ~ mpg + cyl, data = df, family = quasibinomial(link = 'logit')) model2 <- glm(am ~ mpg + cyl, data = df, family = quasibinomial(link = 'probit')) model3 <- glm(am ~ wt + cyl, data = df, family = quasibinomial(link = 'logit')) model4 <- glm(am ~ wt + cyl, data = df, family = quasibinomial(link = 'probit')) models <- list(model1, model2, model3, model4) mfx <- lapply(models, marginaleffects) # 异常调用 modelsummary(mfx, output = 'markdown')
按照警告提示添加shape = ~ term + contrast ~ model参数后,冗余行问题得到改善,但仍存在两个问题:
- 仍会弹出"Objects of class 'NULL' are currently not supported"警告
- 表格额外新增了一列标识对比类型的列,需要隐藏或自定义该列内容
解决方案
1. 消除NULL类不支持警告
该警告是因为marginaleffects返回的原始对象中携带了未赋值的空属性,modelsummary在提取属性时识别到NULL值触发。
处理方式:不要直接将原始marginaleffects对象传入modelsummary,先用tidy()方法将所有边际效应结果转换为标准数据框格式,空属性会被自动剔除:
mfx <- lapply(models, function(x) tidy(marginaleffects(x)))
处理后再调用modelsummary就不会触发NULL相关警告。
2. 隐藏/自定义shape参数生成的额外对比列
不需要保留单独对比列的场景,推荐直接合并term和contrast字段,完全避免使用shape参数,从根源上消除额外列:
mfx <- lapply(models, function(x) { marginaleffects(x) |> tidy() |> # 分类变量的对比信息合并到变量名中,连续变量contrast为NA直接保留原变量名 mutate(term = ifelse(is.na(contrast), term, paste0(term, ": ", contrast))) }) # 直接生成无冗余、无额外列的表格 modelsummary(mfx, output = "markdown")
如果已经使用shape参数需要调整列,可以通过colnames参数重命名对比列,或者通过group_map参数将对比层级合并到行分组中,不单独生成列。
内容的提问来源于stack exchange,提问作者Daniel Sánchez
相关产品推荐
相关产品推荐

