我有一个关于设置 gtsummary 包默认主题的问题。
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
)
我想知道如何设置默认主题以添加 p 值或例如使标签加粗。我尝试了上面的代码,但它不起作用。我知道我可以添加 add_p()
但我想知道我是否可以在主题中执行此操作,这样我在想要添加时就不必输入 add_p
p 值。感谢您的帮助。
最佳答案
更新:
从 gtsummary v1.4.0 开始,您可以使用主题在每个 tbl_summary()
之后设置诸如 add_p()
和 bold_labels()
之类的函数。 p>
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)
由 reprex package 创建于 2021-04-14 (v2.0.0)
旧帖子:
使用主题的 tbl_summary()
之后无法直接自动运行 add_p()
和 bold_labels()
。我认为最好的选择可能是定义一个运行附加函数的新函数。
tbl_summary_p <- function(...) {
tbl_summary(...) %>%
add_p() %>%
bold_labels()
}
gap %>% tbl_summary_p(by = continent)
但是,您可以利用主题将标签加粗。主题允许您使用主题元素 as_gt-lst:addl_cmds
包含任何格式化命令。如果您将下面的主题元素添加到主题列表中,gt 表格的标签行将以粗体显示。
# 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"))))
关于r - 为 gtsummary 包设置默认主题和粗体变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65747694/