使用modelsummary输出mgcv::gam模型摘要时遇参数报错求助
解决modelsummary输出mgcv::gam模型时的系数筛选与格式报错问题
问题分析
你在使用modelsummary输出mgcv::gam模型时,尝试通过coef_omit = "^(?!.*Intercept)"保留截距项,同时搭配shape = term ~ model + statistic参数时报错,原因是当仅保留单个截距项时,modelsummary内部的表格结构逻辑判断会因缺失对比项出现NA值,触发条件判断错误。而移除shape参数后,表格采用长格式输出,避免了这个结构冲突,因此报错消失。
解决方案
下面提供几种稳妥的方法,实现分开输出参数项(截距)和平滑项的需求,同时规避报错:
1. 拆分生成参数项与平滑项表格
输出参数项(截距)表格
直接使用coef_keep指定保留截距(比coef_omit更直观,避免正则表达式的潜在问题),同时调整参数确保格式正常:
library(mgcv) library(modelsummary) # 生成示例数据与模型 dat <- gamSim(1, n = 4000, dist = "normal", scale = 2) mod <- gam(y ~ s(x0) + s(x1) + s(x2), data = dat) # 生成参数项(截距)表格 modelsummary(mod, estimate = "estimate", statistic = c("Std.Error" = "std.error", "t-value" = "statistic", "p-value" = "p.value"), coef_keep = "Intercept", # 精准保留截距项 shape = term ~ model + statistic, gof_map = NA)
输出平滑项表格
平滑项的核心统计量是有效自由度(EDF)、卡方值和P值,直接筛选掉截距项即可:
# 生成平滑项表格 modelsummary(mod, estimate = NULL, # 平滑项不需要点估计值 statistic = c("EDF" = "edf", "Chi2" = "statistic", "P-value" = "p.value"), coef_omit = "Intercept", # 剔除截距,保留平滑项 shape = term ~ model + statistic, gof_map = NA)
2. 先提取tidy数据再传入modelsummary(更灵活)
通过broom::tidy分别提取参数项和平滑项的结构化数据,再传入modelsummary,彻底规避内部结构冲突:
library(broom) library(dplyr) # 提取参数项(截距)的tidy数据 tidy_param <- tidy(mod, type = "parametric") %>% filter(term == "(Intercept)") # 生成参数项表格 modelsummary(tidy_param, estimate = "estimate", statistic = c("Std.Error" = "std.error", "t-value" = "statistic", "p-value" = "p.value"), shape = term ~ model + statistic, gof_map = NA) # 提取平滑项的tidy数据 tidy_smooth <- tidy(mod, type = "smooth") # 生成平滑项表格 modelsummary(tidy_smooth, columns = c("term", "edf", "statistic", "p.value"), rename = c("term" = "平滑项", "edf" = "有效自由度", "statistic" = "卡方值", "p.value" = "P值"), fmt = 3) # 统一保留3位小数
额外建议
如果不需要严格拆分两个表格,modelsummary支持对gam模型的参数项和平滑项自动分组展示,只需去掉系数筛选参数,即可生成包含两部分的完整表格,符合学术出版规范:
modelsummary(mod, statistic = c("Std.Error" = "std.error", "t-value" = "statistic", "p-value" = "p.value", "EDF" = "edf", "Chi2" = "statistic"), gof_map = c("r.squared", "adj.r.squared", "nobs"))
内容的提问来源于stack exchange,提问作者mpschramm
相关产品推荐
相关产品推荐

