You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在gtsummary中提取检验的读者友好名称至独立列?

解决方案:将gtsummary检验名称替换为读者友好格式

完全可以实现这个需求,gtsummary内部已经维护了检验函数名与友好名称的映射关系,我们可以直接复用这个映射来替换test_name列的内容,具体步骤如下:

方法1:复用gtsummary内置映射表

gtsummary内部有一个test_name_lookup对象,存储了所有支持的检验函数对应的友好名称,直接通过表连接替换即可:

library(gtsummary)
library(dplyr)

# 你的原始代码
df <- data.frame(rnorm(10),rnorm(10), sample(c("orange","pink","green"), size = 10, replace = TRUE),sample(c(TRUE, FALSE), size = 10, replace = TRUE))
names(df) <- c("a","b","c","outcome")
preds <- c("a","b","c")

gt <- df %>% select(all_of(preds), outcome) %>%
  tbl_summary(by = outcome, percent = 'row') %>%
  add_p() 

# 获取内置检验名称映射,替换test_name列
gt_friendly <- gt %>%
  modify_table_body(
    ~ .x %>%
      left_join(gtsummary:::test_name_lookup, by = c("test_name" = "test")) %>%
      mutate(test_name = coalesce(label, test_name)) %>%
      select(-label)
  ) %>%
  modify_header(statistic ~ "**Test Statistic**", 
                test_name ~ "**Test Used**")

# 查看结果
gt_friendly

方法2:自定义映射表(可选)

如果需要更灵活地控制显示名称,可以手动创建映射表:

# 自定义检验名称映射
custom_test_map <- tibble::tibble(
  test = c("fisher.test", "t.test", "wilcox.test", "chisq.test"),
  label = c("Fisher's exact test", "Student's t-test", "Wilcoxon rank-sum test", "Pearson's chi-squared test")
)

# 替换并调整表头
gt_friendly_custom <- gt %>%
  modify_table_body(
    ~ .x %>%
      left_join(custom_test_map, by = c("test_name" = "test")) %>%
      mutate(test_name = coalesce(label, test_name)) %>%
      select(-label)
  ) %>%
  modify_header(statistic ~ "**Test Statistic**", 
                test_name ~ "**Test Used**")

两种方法都能将test_name列的函数名(如fisher.test)替换为脚注中使用的读者友好名称(如Fisher's exact test)。

内容的提问来源于stack exchange,提问作者purpleblade98

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 12:57:53