向gtsummary表添加自定义选项

问题描述

我试图弄清楚如何在使用gtsummary时添加自定义选项,例如,用于pvalue,标题等的星号。

这是使用基本mtcars数据的可重现示例,以防更高效...

library(tidyverse)
library(gtsummary)
#> Warning: package 'gtsummary' was built under R version 4.0.3
#> #Uighur

r1 <- lm(mpg ~ wt + cyl,data = mtcars) %>% 
  tbl_regression(exponentiate = TRUE)

r2 <- lm(hp ~ wt + cyl,data = mtcars) %>% 
  tbl_regression(exponentiate = TRUE)

r3 <- lm(qsec ~ wt + cyl,data = mtcars) %>% 
  tbl_regression(exponentiate = TRUE)


tbl_merge(list(r1,r2,r3),tab_spanner = c("**MPG**","**Horsepower**","**Seconds**"))

解决方法

  1. 您可以选择使用tbl_regression(pvalue_fun=)参数设置p值格式的方式。下面的例子。您还可以使用gtsummary主题设置将在整个包中使用的默认pvalue格式设置功能。 http://www.danieldsjoberg.com/gtsummary/articles/themes.html
  2. 要添加标题/表格标题,请首先使用as_gt()函数将gtsummary表转换为gt对象,然后使用可用的many gt函数添加标题。下面的示例。
library(tidyverse)
library(gtsummary)

# round and star p-values
pvalue_stars <- function(x) {
  # you can round however you'd like
  x_chr <- style_pvalue(x,digits = 2)
  # x_chr <- style_number(x,digits = 3) # another example of how you could round
  
  # add stars to low p-values
  dplyr::case_when(
    x < 0.01 ~ paste0(x_chr,"***"),x < 0.05 ~ paste0(x_chr,"**"),x < 0.10 ~ paste0(x_chr,"*"),TRUE ~ x_chr
  )
}
pvalue_stars(c(0.001,0.01,0.09,0.2))

# create a tibble with one row per model
tibble(outcome = c("mpg","hp","qsec")) %>%
  rowwise() %>%
  mutate(
    tbl = 
      lm(str_glue("{outcome} ~ wt + cyl"),data = mtcars) %>%
      tbl_regression(exponentiate = TRUE,# specify the pvalue formatting function
                     pvalue_fun = pvalue_stars) %>%
      list()
  ) %>%
  # pull tbl_regression() objects into single merged table
  pull(tbl) %>%
  tbl_merge(tab_spanner = c("**MPG**","**Horsepower**","**Seconds**")) %>%
  # add table captions
  as_gt() %>%
  gt::tab_header(title = "Table 1. Car Regression Model",subtitle = "Highly Confidential")

enter image description here