求助:用gtsummary生成带90%CI效应量及定性指标的汇总表
解决gtsummary中使用effectsize计算效应量的报错及添加定性量级
首先必须要感谢Daniel Sjoberg和gtsummary的开发者们,这个包确实是R中处理统计结果报告的高效工具!针对你遇到的报错和需求,我整理了以下解决方案:
一、解决Please provide data argument报错问题
你遇到的报错是因为add_stat传递给自定义函数的参数格式和你定义的不匹配:gtsummary的add_stat会把当前分析的数据集以x参数传递给自定义函数,而不是你定义的data。同时,调用cohens_d时用公式+data参数的方式更规范,能避免直接提取列的潜在问题。
修改后的基础效应量计算函数如下:
CohenD <- function(x, variable, by, ...) { # 使用公式+data参数调用cohens_d,符合effectsize的标准用法 ES <- effectsize::cohens_d( formula = as.formula(paste(variable, "~", by)), data = x, ci = .90, pooled_sd = TRUE, paired = FALSE, correction = TRUE ) # 格式化统计量和置信区间 est <- style_sigfig(abs(ES$Cohens_d)) ci_lower <- style_sigfig(ES$CI_low) ci_upper <- style_sigfig(ES$CI_high) # 返回效应量+CI的组合文本 str_glue("{est} ({ci_lower}, {ci_upper})") }
二、添加效应量定性量级
要在效应量后添加Cohen(1988)的定性解释,只需要在自定义函数中加入effectsize::interpret_d的计算,并把结果拼接进去即可。更新后的函数如下:
CohenD_with_interpret <- function(x, variable, by, ...) { ES <- effectsize::cohens_d( formula = as.formula(paste(variable, "~", by)), data = x, ci = .90, pooled_sd = TRUE, paired = FALSE, correction = TRUE ) # 格式化统计量和CI est <- style_sigfig(abs(ES$Cohens_d)) ci_lower <- style_sigfig(ES$CI_low) ci_upper <- style_sigfig(ES$CI_high) # 计算定性量级标签 interpret_label <- effectsize::interpret_d(ES$Cohens_d, rules = "cohen1988") # 返回效应量+CI+定性解释的组合文本 str_glue("{est} ({ci_lower}, {ci_upper}) [{interpret_label}]") }
三、最终完整代码
把更新后的函数替换到你的表格代码中,完整可运行代码如下:
library(gtsummary) library(effectsize) library(tidyverse) # 定义带定性解释的效应量函数 CohenD_with_interpret <- function(x, variable, by, ...) { ES <- effectsize::cohens_d( formula = as.formula(paste(variable, "~", by)), data = x, ci = .90, pooled_sd = TRUE, paired = FALSE, correction = TRUE ) est <- style_sigfig(abs(ES$Cohens_d)) ci_lower <- style_sigfig(ES$CI_low) ci_upper <- style_sigfig(ES$CI_high) interpret_label <- effectsize::interpret_d(ES$Cohens_d, rules = "cohen1988") str_glue("{est} ({ci_lower}, {ci_upper}) [{interpret_label}]") } # 生成最终分析表格 Table <- trial %>% select(trt, age) %>% tbl_summary( by = trt, missing = "no", label = list(age ~ "Age (yrs)"), statistic = list(all_continuous() ~ "{mean} ± {sd}"), digits = list(all_continuous() ~ c(1,1)) ) %>% bold_labels() %>% italicize_levels() %>% add_p( test = everything() ~ t.test, pvalue_fun = partial(style_pvalue, digits = 2) ) %>% add_stat( fns = everything() ~ CohenD_with_interpret, fmt_fun = NULL, header = "**ES (90% CI) [Magnitude]**" ) %>% modify_footnote(add_stat_1 ~ "Hedges's g (90% CI) with Cohen (1988) magnitude interpretation") %>% modify_header(label = "**Variables**", stat_by = "**{level}** (N= {n})") Table
关键调整点说明
- 把自定义函数的第一个参数从
data改为x,匹配gtsummaryadd_stat的参数传递逻辑 - 使用
as.formula(paste(variable, "~", by))动态生成公式,结合data=x调用cohens_d,避免直接提取列的错误 - 添加
interpret_d计算定性量级,并将其与效应量、CI拼接返回 - 调整了表头和脚注,明确说明表格中包含定性解释信息
内容的提问来源于stack exchange,提问作者Cristiano
相关产品推荐
相关产品推荐

