如何使用gtsummary在均值行下方添加置信区间(CI)
解决方案
要实现将均值置信区间(CI)作为单独行添加到均值(SD)行下方的效果,你可以使用gtsummary包的add_stat()函数,自定义计算CI并指定插入位置,替代默认生成列的add_ci()。以下是修改后的代码:
library(gtsummary) library(tidyverse) data %>% tbl_summary( by = Cohort, type = all_continuous() ~ "continuous2", include = c(`Total value 1`), statistic = all_continuous() ~ c("{mean} ({sd})", "{median} ({p25}, {p75})", "{min}, {max}"), missing = "no" ) %>% # 添加95%置信区间作为单独统计行 add_stat( fns = all_continuous() ~ function(x) { # 计算均值的95%CI,可通过conf.level调整置信水平 ci_result <- t.test(x, conf.level = 0.95)$conf.int glue::glue("{round(ci_result[1], 2)}, {round(ci_result[2], 2)}") }, # 指定CI行插入到"Mean (SD)"行的下方 location = ~ after_stat(row_type == "statistic", row_label == "Mean (SD)"), # 设置CI行的标签 label = all_continuous() ~ "95% CI" ) %>% add_overall(last = TRUE) %>% bold_labels() %>% add_stat_label(label = all_continuous() ~ c("Mean (SD)", "Median (IQR)", "Min, Max")) %>% as_gt()
关键说明
add_stat()函数允许自定义统计量并插入到指定位置,这里通过匿名函数调用t.test()计算均值的95%置信区间。- 可通过修改
round()的参数调整CI的小数位数,或在t.test()中设置conf.level更改置信水平(如0.90对应90%CI)。 location参数精准控制CI行插入到均值行的下方,匹配目标表格的样式。
内容的提问来源于stack exchange,提问作者Shu Cao
相关产品推荐
相关产品推荐

