Pan Qing
Pan Qing

Reputation: 129

Why the function "round" does not work on the digits of p-value? and How to adjust the digits of percentage in the summary tables using "gtsummary"?

When I was creating a " custom pvalue function to add_p()" , I tried to adjust the digits of p-value but found that the function "round" dose not work. (see the code "result$p <- round(result$p, 3)")

Besides, I found I can not change the digits of the percentage of counts numbers in the summary table.


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

Upvotes: 3

Views: 1919

Answers (1)

Daniel D. Sjoberg
Daniel D. Sjoberg

Reputation: 11679

First, can I please compliment you on the table you constructed: I am very impressed!

To change the formatting of the p-value in the table, use the add_p(pvalue_fmt=) argument to pass a function. The function should take a numeric vector, and return a formatted/rounded character vector.

To modify the formatting percentages use the tbl_summary(digits=) argument.

Example below!

library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.4.2'

tbl <-
  trial %>%
  dplyr::select(trt, age, grade) %>%
  tbl_summary(
    by = trt,
    # show percentages to 1 decimal place
    digits = all_categorical() ~ c(0, 1)
  ) %>%
  # rounding p-values to 3 decimal places
  add_p(pvalue_fun = function(x) style_number(x, digits = 3))

enter image description here Created on 2021-07-23 by the reprex package (v2.0.0)

Upvotes: 5

Related Questions