为什么函数“舍入”不适用于p值的数字?以及如何使用“ gtsummary”调整汇总表中百分比的位数?

时间:2020-05-06 15:25:16

标签: gtsummary

当我创建“ add_p()的自定义pvalue函数”时,我试图调整p值的位数,但是发现“舍入”函数不起作用。 (请参见代码“ result $ p <-round(result $ p,3)”)

此外,我发现我无法更改汇总表中计数数字百分比的数字。


ttest1 <- function(data, variable, by, ...) {
  result <- list()
  result$p <- stats::t.test(data[[variable]] ~ data[[by]])$statistic
  result$p <- round(result$p, 3)
  result$test <- "t test"
  result
}

ttest2 <- function(data, variable, by, ...) {
  result <- list()
  result$p <- stats::t.test(data[[variable]] ~ data[[by]])$p.value
  result$p <- round(result$p, 3)
  result$test <- "t test"
  result
}


add_p_ex1 <-trial[c("age","grade", "response", "trt")] %>%
  tbl_summary(by = trt,
              statistic = list(all_continuous() ~ "{mean} ± {sd}",
                               all_categorical() ~ "{n} ({p})"),
              digits = list(all_continuous() ~ c(2, 2))) %>%
  add_p(test = list(all_continuous() ~ "ttest1", all_categorical() ~ "chisq1")) %>% 
  modify_header(p.value = md("**t/X2**"))


add_p_ex2 <-
  tbl_summary(by = trt,
              statistic = list(all_continuous() ~ "{mean} ± {sd}",
                               all_categorical() ~ "{n} ({p})"),
              digits = list(all_continuous() ~ c(2, 2))) %>%
  add_p(test = list(all_continuous() ~ "ttest1", all_categorical() ~ "chisq2"))

tbl_merge(list(add_p_ex1, add_p_ex2)) %>%
  as_gt(include = -tab_spanner) %>%
  cols_hide(columns = vars(stat_1_2, stat_2_2))

enter image description here

1 个答案:

答案 0 :(得分:1)

首先,请您在您制作的桌子上称赞我,我印象深刻!

要更改表中p值的格式,请使用add_p(pvalue_fmt=)参数传递函数。该函数应采用数字矢量,并返回格式化/四舍五入的字符矢量。

我们仍在为用户修改tbl_summary()输出中百分比的默认格式的最佳方法。在gtsummary的开发版本中,我们引入了主题,使您可以指示输出显示方式的首选项。我在下面提供了一个示例,如果您想了解更多信息,这是小插图的链接。 (仅供参考,您还可以设置主题的p值格式功能。) http://www.danieldsjoberg.com/gtsummary/dev/articles/themes.html

# install dev version 
remotes::install_github("ddsjoberg/gtsummary")

# load gtsummary package
library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.3.0.9008'

# set theme where percentages are rounded to 1 decimal place
set_gtsummary_theme(list(
  "tbl_summary-fn:percent_fun" = function(x) sprintf(x * 100, fmt='%#.1f')
))

# creating summary table
tbl <-
  trial %>%
  dplyr::select(trt, age, grade) %>%
  tbl_summary(by = trt) %>%
  # rounding p-values to 3 decimal places
  add_p(pvalue_fun = function(x) sprintf(x, fmt='%#.3f'))

enter image description here reprex package(v0.3.0)于2020-05-06创建