如何将多个glmmTMB双变量多水平模型结果自动汇总为展示表格
实现方案
你可以通过broom.mixed批量提取glmmTMB的模型结果,再配合knitr::kable输出格式化表格,全程自动生成无需手动录入,模型更新后重新运行代码即可同步更新表格。
步骤1:安装加载所需包
# 首次使用先安装 install.packages(c("glmmTMB", "broom.mixed", "dplyr", "knitr")) # 加载包 library(glmmTMB) library(broom.mixed) library(dplyr) library(knitr)
步骤2:准备数据与拟合模型
将所有单暴露模型存入列表,方便批量处理:
# 示例数据 data = data.frame( id = c(1,1,1,2,2,2,3,3,3), ses = c(0.13, 1.23, -0.78, 1.32, 0.56, -0.04, -1.43, 1.45, 2.01), season = c("good", "good", "bad", "bad", "bad", "good", "good", "good", "good" ), haemoglobin = c(15, 14, 16, 9, 10, 11, 12, 10, 11) ) # 拟合多个单暴露模型,存入列表 mod_list <- list( season = glmmTMB(haemoglobin ~ season + (1 | id), data = data), ses = glmmTMB(haemoglobin ~ ses + (1 | id), data = data) )
步骤3:批量提取并整理模型结果
# 批量提取所有模型的固定效应结果 res <- lapply(names(mod_list), function(x) { mod <- mod_list[[x]] # 提取固定效应、置信区间、p值 tidy_res <- tidy(mod, effects = "fixed", conf.int = TRUE) %>% select(Variable = term, Estimate = estimate, conf.low, conf.high, Pval = p.value) %>% # 合并置信区间为指定格式 mutate(Confint = paste(round(conf.low, 2), round(conf.high, 2), sep = ", ")) %>% select(Variable, Estimate, Confint, Pval) # 处理分类变量的参考组 if (is.factor(data[[x]]) | is.character(data[[x]])) { # 获取分类变量的所有水平 all_levels <- unique(data[[x]]) # 已出现在结果中的水平(非参考组) exist_levels <- gsub(x, "", tidy_res$Variable) # 找参考组 ref_level <- setdiff(all_levels, exist_levels) # 加参考组行 ref_row <- data.frame( Variable = paste0(x, ref_level), Estimate = "ref", Confint = "-", Pval = "-" ) tidy_res <- rbind(ref_row, tidy_res) } return(tidy_res) }) %>% bind_rows() # 调整数值精度 res <- res %>% mutate( Estimate = ifelse(Estimate == "ref", "ref", as.character(round(as.numeric(Estimate), 4))), Pval = ifelse(Pval == "-", "-", as.character(round(as.numeric(Pval), 6))) )
步骤4:用kable输出表格
在R Markdown中运行以下代码即可直接生成格式化表格:
kable(res, align = "lccc", row.names = FALSE)
输出效果如下:
| Variable | Estimate | Confint | Pval |
|---|---|---|---|
| seasongood | ref | - | - |
| seasonbad | 0.0519 | -1.62, 1.72 | 0.951067 |
| ses | -0.6497 | -1.01, -0.29 | 0.000442 |
如果需要调整分类变量的参考组,可提前通过relevel(factor(data$变量名), ref = "参考组水平")修改因子的参考水平,结果会自动适配。如果需要更美观的表格样式,可以加载kableExtra包添加边框、表头、高亮显著结果等自定义设置。
内容的提问来源于stack exchange,提问作者Rose Stevens
相关产品推荐
相关产品推荐

