如何从gtsummary包的tbl_summary()中获取统计检验详细结果?
获取gtsummary表格中检验的详细统计结果
gtsummary 默认的 add_p() 仅输出p值,但可以通过自定义p值格式化函数,直接在表格中展示Kruskal-Wallis、卡方检验的完整统计结果(包括统计量、自由度、p值),无需单独运行每个检验。
修改后的完整代码
library(tidyverse) library(gtsummary) library(palmerpenguins) library(glue) # 需加载glue用于字符串拼接 # 自定义函数:根据检验类型格式化输出完整结果 format_test_details <- function(p_val, test_obj) { # 处理Kruskal-Wallis检验 if (inherits(test_obj, "htest") && test_obj$method == "Kruskal-Wallis rank sum test") { h_stat <- round(test_obj$statistic, 2) df <- test_obj$parameter formatted_p <- style_pvalue(p_val, digits = 3) glue("H({df}) = {h_stat}, {formatted_p}") } # 处理卡方检验 else if (inherits(test_obj, "htest") && grepl("Chi-squared test", test_obj$method)) { chi_stat <- round(test_obj$statistic, 2) df <- test_obj$parameter formatted_p <- style_pvalue(p_val, digits = 3) glue("χ²({df}) = {chi_stat}, {formatted_p}") } # 其他检验默认输出格式化后的p值 else { style_pvalue(p_val, digits = 3) } } penguins %>% tbl_summary( by = species, missing = "no", statistic = list(all_continuous() ~ "{mean} {sd}"), label = list(bill_length_mm = "Bill length (mm)") ) %>% add_p( all_continuous() ~ "kruskal.test", all_categorical() ~ "chisq.test", # 明确分类变量用卡方检验 pvalue_fun = function(x) format_test_details(x, attr(x, "test_obj")), include = everything() ) %>% bold_p()
关键说明
- 自定义函数
format_test_details通过attr(x, "test_obj")获取add_p()生成的检验对象,从中提取统计量、自由度等信息,拼接成你需要的格式。 - 针对连续变量的Kruskal-Wallis检验,输出格式为
H(自由度) = 统计量, p值;针对分类变量的卡方检验,输出格式为χ²(自由度) = 统计量, p值。 - 需提前加载
glue包用于字符串拼接,如果未安装可先运行install.packages("glue")。
内容的提问来源于stack exchange,提问作者always.learning
相关产品推荐
相关产品推荐

