Reputation: 243
I have a question regarding setting the default theme for the gtsummary package.
library(tidyverse)
library(gtsummary)
library(gapminder)
gap <- gapminder %>%
dplyr::mutate_all(~ifelse(
sample(c(TRUE, FALSE), size = length(.), replace = TRUE, prob = c(0.8, 0.2)),
as.character(.),
NA)
) %>%
dplyr::mutate_at(vars(year:gdpPercap), ~as.numeric(.)
) %>%
dplyr::mutate(gdpPercap = ifelse(gdpPercap > median(gdpPercap, na.rm = TRUE), "high", "low"))
my_theme <-
list(
"tbl_summary-str:default_con_type" = "continuous2",
"tbl_summary-str:continuous_stat" = c("{median} ({p25} - {p75})",
"{mean} ({sd})",
"{min} - {max}"),
"tbl_summary-str:categorical_stat" = "{n} / {N} ({p}%)",
"style_number-arg:big.mark" = "",
"add_p.tbl_summary-attr:test.categorical" = "",
"tbl_summary-fn:percent_fun" = function(x) style_percent(x, digits = 3),
"add_p.tbl_summary-attr:test.categorical" = "chisq.test"
)
gap %>%
gtsummary::tbl_summary(
by = continent
)
I would like to know how I can set the default theme to add p values or for example make the labels bold. I tried the code above but it did not work. I know that I can add add_p()
but I would like to know if I can do that in the theme so I don't have to type add_p
when wanting to add p-values. Thank you for your help.
Upvotes: 2
Views: 1130
Reputation: 11754
UPDATE:
As of gtsummary v1.4.0, you can set functions like add_p()
and bold_labels()
after each tbl_summary()
using themes.
library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.4.0'
# theme to always run add_p() and bold_labels() after tbl_summary()
list(
"tbl_summary-fn:addnl-fn-to-run" =
function(x) {
if (!is.null(x$by)) x <- add_p(x) # add_p if there is a by variable
bold_labels(x) # bold labels and return table
}
) %>%
set_gtsummary_theme()
tbl <-
trial %>%
select(age, grade, trt) %>%
tbl_summary(by = trt)
Created on 2021-04-14 by the reprex package (v2.0.0)
OLD POST:
There is no way to directly run add_p()
and bold_labels()
automatically after tbl_summary()
using themes. I think the your best bet may be to define a new function that runs the additional functions.
tbl_summary_p <- function(...) {
tbl_summary(...) %>%
add_p() %>%
bold_labels()
}
gap %>% tbl_summary_p(by = continent)
You can, however, utilize the themes to bold the labels. Themes allow you to include any formatting commands using theme element as_gt-lst:addl_cmds
. If you add the theme element below to your theme list, gt tables will have the label rows bolded.
# bold labels for gt output
"as_gt-lst:addl_cmds" =
list(tab_spanner = expr(gt::tab_style(style = gt::cell_text(weight = "bold"),
locations = gt::cells_body(columns = gt::vars(label),
rows = row_type == "label"))))
Upvotes: 2