问题
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))
回答1:
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.
We're still working out the best way for users to modify the default formatting of percentages in tbl_summary()
output. In the development version of gtsummary, we've introduced themes that allow you to indicate preferences for how output is displayed. I've included an example below, and here's the link to the vignette if you'd like to read more. (FYI you can set p-value formatting functions with themes as well.)
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'))
Created on 2020-05-06 by the reprex package (v0.3.0)
来源:https://stackoverflow.com/questions/61638996/why-the-function-round-does-not-work-on-the-digits-of-p-value-and-how-to-adju