![](/img/trans.png)
[英]Set theme for categorical and continuous variables in gtsummary package for tbl_summary function in R
[英]Set values default theme and bold variables for gtsummary package
我有一個關於為 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
)
我想知道如何設置默認主題以添加 p 值或例如將標簽設為粗體。 我嘗試了上面的代碼,但它沒有用。 我知道我可以添加add_p()
但我想知道我是否可以在主題中這樣做,這樣我就不必在想要添加 p 值時鍵入add_p
。 謝謝您的幫助。
更新:從 gtsummary v1.4.0 開始,您可以在使用主題的每個tbl_summary()
) 之后設置add_p()
和bold_labels()
等函數。
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 (v2.0.0) 創建於 2021-04-14
舊帖子:無法在使用主題的tbl_summary()
() 之后直接自動運行add_p()
和bold_labels()
。 我認為您最好的選擇可能是定義一個運行附加功能的新 function。
tbl_summary_p <- function(...) {
tbl_summary(...) %>%
add_p() %>%
bold_labels()
}
gap %>% tbl_summary_p(by = continent)
但是,您可以利用主題來加粗標簽。 主題允許您使用主題元素as_gt-lst:addl_cmds
包含任何格式化命令。 如果將下面的主題元素添加到主題列表中,gt 表會將 label 行加粗。
# 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"))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.