Repository navigation
Expand file tree
/
Copy paththeme_gtsummary.R
More file actions
452 lines (428 loc) · 18.8 KB
/
Copy paththeme_gtsummary.R
File metadata and controls
452 lines (428 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
#' Available gtsummary themes
#'
#' The following themes are available to use within the gtsummary package.
#' Print theme elements with `theme_gtsummary_journal(set_theme = FALSE) |> print()`.
#' Review the [themes vignette](https://www.danieldsjoberg.com/gtsummary/articles/themes.html)
#' for details.
#'
#' @param set_theme (scalar `logical`)\cr
#' Logical indicating whether to set the theme. Default is `TRUE`.
#' When `FALSE` the named list of theme elements is returned invisibly
#' @param font_size (scalar `numeric`)\cr
#' Numeric font size for compact theme.
#' Default is 13 for gt tables, and 8 for all other output types
#'
#' @name theme_gtsummary
#' @section Themes:
#' - `theme_gtsummary_journal(journal)`
#' - `"jama"` _The Journal of the American Medical Association_
#' - Round large p-values to 2 decimal places; separate confidence intervals with `"ll to ul"`.
#' - `tbl_summary()` Doesn't show percent symbol; use em-dash to separate IQR; run `add_stat_label()`
#' - `tbl_regression()`/`tbl_uvregression()` show coefficient and CI in same column
#' - `"lancet"` _The Lancet_
#' - Use mid-point as decimal separator; round large p-values to 2 decimal places; separate confidence intervals with `"ll to ul"`.
#' - `tbl_summary()` Doesn't show percent symbol; use em-dash to separate IQR
#' - `"nejm"` _The New England Journal of Medicine_
#' - Round large p-values to 2 decimal places; separate confidence intervals with `"ll to ul"`.
#' - `tbl_summary()` Doesn't show percent symbol; use em-dash to separate IQR
#' - `"qjecon"` _The Quarterly Journal of Economics_
#' - `tbl_summary()` all percentages rounded to one decimal place
#' - `tbl_regression()`,`tbl_uvregression()` add significance stars with `add_significance_stars()`;
#' hides CI and p-value from output
#' - For flextable and huxtable output, the coefficients' standard error is placed below. For gt, it is placed to the right.
#' - `theme_gtsummary_compact()`
#' - tables printed with gt, flextable, kableExtra, or huxtable will be compact with smaller font size and reduced cell padding
#' - `theme_gtsummary_printer(print_engine)`
#' - Use this theme to permanently change the default printer.
#' - `theme_gtsummary_continuous2()`
#' - Set all continuous variables to summary type `"continuous2"` by default
#' - `theme_gtsummary_mean_sd()`
#' - Set default summary statistics to mean and standard deviation in `tbl_summary()`
#' - Set default continuous tests in `add_p()` to t-test and ANOVA
#' - `theme_gtsummary_eda()`
#' - Set all continuous variables to summary type `"continuous2"` by default
#' - In `tbl_summary()` show the median, mean, IQR, SD, and Range by default
#'
#' Use `reset_gtsummary_theme()` to restore the default settings
#'
#' Review the [themes vignette](https://www.danieldsjoberg.com/gtsummary/articles/themes.html)
#' to create your own themes.
#' @examples
#' # Setting JAMA theme for gtsummary
#' theme_gtsummary_journal("jama")
#' # Themes can be combined by including more than one
#' theme_gtsummary_compact()
#'
#' trial |>
#' select(age, grade, trt) |>
#' tbl_summary(by = trt) |>
#' as_gt()
#'
#' # reset gtsummary themes
#' reset_gtsummary_theme()
#' @seealso [Themes vignette](https://www.danieldsjoberg.com/gtsummary/articles/themes.html)
#' @seealso [set_gtsummary_theme()], [reset_gtsummary_theme()]
NULL
# ------------------------------------------------------------------------------
#' @rdname theme_gtsummary
#' @export
#' @param journal String indicating the journal theme to follow. One of
#' `c("jama", "lancet", "nejm", "qjecon")`. Details below.
theme_gtsummary_journal <- function(journal = c("jama", "lancet", "nejm", "qjecon"),
set_theme = TRUE) {
journal <- match.arg(journal)
if (journal == "jama") {
lst_theme <-
list(
"pkgwide-str:theme_name" = "JAMA",
"pkgwide-fn:pvalue_fun" = label_style_pvalue(digits = 2),
"pkgwide-fn:prependpvalue_fun" = label_style_pvalue(digits = 2, prepend_p = TRUE),
"pkgwide-str:ci.sep" = " to ",
"style_number-arg:decimal.mark" = ".",
"style_number-arg:big.mark" = ",",
"add_stat_label-arg:location" = "row",
"tbl_summary-arg:statistic" = list(all_continuous() ~ "{median} ({p25} \U2013 {p75})",
all_categorical() ~ "{n} ({p})"),
"tbl_svysummary-arg:statistic" = list(all_continuous() ~ "{median} ({p25} \U2013 {p75})",
all_categorical() ~ "{n} ({p})"),
"tbl_summary-fn:addnl-fn-to-run" = function(x) {
add_stat_label(x) |>
modify_table_body(
\(x) {
if ("stat_label" %in% names(x)) {
x$stat_label <- gsub("Q1 \U2013 Q3", "IQR", x = x$stat_label)
}
x
}
)
},
"tbl_svysummary-fn:addnl-fn-to-run" = function(x) {
add_stat_label(x) |>
modify_table_body(
\(x) {
if ("stat_label" %in% names(x)) {
x$stat_label <- gsub("Q1 \U2013 Q3", "IQR", x = x$stat_label)
}
x
}
)
},
"add_difference-fn:addnl-fn-to-run" = function(x) {
# merging coef and CI columns, if error, returning x unaltered
tryCatch(
{
new_header_text <-
paste0(
x$table_styling$header |> dplyr::filter(.data$column == "estimate") |> dplyr::pull("label"),
" **(**",
x$table_styling$header |> dplyr::filter(.data$column == "conf.low") |> dplyr::pull("label"),
"**)**"
)
x %>%
# merge estimate and CI into one cell
modify_column_merge(
rows = !!expr(.data$variable %in% !!x$table_body$variable &
!is.na(.data$estimate)),
pattern = "{estimate} ({conf.low} to {conf.high})"
) |>
# update column header
modify_header(estimate = new_header_text)
},
error = function(e) x
)
},
"tbl_regression-fn:addnl-fn-to-run" = function(x) {
# merging coef and CI columns, if error, returning x unaltered
tryCatch(
{
new_header_text <-
paste0(
x$table_styling$header|> dplyr::filter(.data$column == "estimate") |> dplyr::pull("label"),
" **(", style_number(x$inputs$conf.level, scale = 100), "% CI)**"
)
x %>%
# merge estimate and CI into one cell
modify_column_merge(
rows = !!expr(.data$variable %in% !!x$table_body$variable &
!is.na(.data$estimate) &
!.data$reference_row %in% TRUE),
pattern = "{estimate} ({conf.low} to {conf.high})"
) |>
# update column header
modify_header(estimate = new_header_text)
},
error = function(e) x
)
}
)
} else if (journal == "nejm") {
lst_theme <-
list(
"pkgwide-str:theme_name" = "New England Journal of Medicine",
"pkgwide-fn:pvalue_fun" = label_style_pvalue(digits = 2),
"pkgwide-fn:prependpvalue_fun" = label_style_pvalue(digits = 2, prepend_p = TRUE),
"style_number-arg:decimal.mark" = ".",
"style_number-arg:big.mark" = ",",
"tbl_summary-arg:statistic" = list(all_continuous() ~ "{median} ({p25} \U2013 {p75})",
all_categorical() ~ "{n} ({p})"),
"pkgwide-str:ci.sep" = " to ",
"tbl_summary-fn:addnl-fn-to-run" = function(x) {
x$table_styling$footnote_header$footnote <-
gsub("Q1 \U2013 Q3", "IQR", x = x$table_styling$footnote_header$footnote)
x
}
)
} else if (journal == "lancet") {
lst_theme <-
list(
"pkgwide-str:theme_name" = "The Lancet",
"pkgwide-fn:pvalue_fun" =
function(x, prepend_p = FALSE) {
p_fmt <-
dplyr::case_when(
# allowing some leeway for numeric storage errors
x > 1 + 1e-15 ~ NA_character_,
x < 0 - 1e-15 ~ NA_character_,
x > 0.99 ~ paste0(">", gtsummary::style_number(x = 0.99, digits = 2)),
cards::round5(x, digits = 2) >= 0.10 ~ gtsummary::style_number(x, digits = 2),
cards::round5(x, digits = 3) >= 0.01 ~ gtsummary::style_number(x, digits = 3),
x >= 0.0001 ~ gtsummary::style_number(x, digits = 4),
x < 0.0001 ~ paste0("<", gtsummary::style_number(x = 0.0001, digits = 4))
)
# prepending a p = in front of value
if (prepend_p == TRUE) {
p_fmt <- dplyr::case_when(
is.na(p_fmt) ~ NA_character_,
substr(p_fmt, start = 1L, stop = 1L) %in% c("<", ">") ~ paste0("p", p_fmt),
TRUE ~ paste0("p=", p_fmt)
)
}
attributes(p_fmt) <- attributes(x)
return(p_fmt)
},
"pkgwide-fn:prependpvalue_fun" =
function(x, prepend_p = TRUE) {
p_fmt <-
dplyr::case_when(
# allowing some leeway for numeric storage errors
x > 1 + 1e-15 ~ NA_character_,
x < 0 - 1e-15 ~ NA_character_,
x > 0.99 ~ paste0(">", gtsummary::style_number(x = 0.99, digits = 2)),
cards::round5(x, digits = 2) >= 0.10 ~ gtsummary::style_number(x, digits = 2),
cards::round5(x, digits = 3) >= 0.01 ~ gtsummary::style_number(x, digits = 3),
x >= 0.0001 ~ gtsummary::style_number(x, digits = 4),
x < 0.0001 ~ paste0("<", gtsummary::style_number(x = 0.0001, digits = 4))
)
# prepending a p = in front of value
if (prepend_p == TRUE) {
p_fmt <- dplyr::case_when(
is.na(p_fmt) ~ NA_character_,
substr(p_fmt, start = 1L, stop = 1L) %in% c("<", ">") ~ paste0("p", p_fmt),
TRUE ~ paste0("p=", p_fmt)
)
}
attributes(p_fmt) <- attributes(x)
return(p_fmt)
},
"tbl_summary-arg:statistic" = list(all_continuous() ~ "{median} ({p25} \U2013 {p75})",
all_categorical() ~ "{n} ({p}%)"),
"style_number-arg:decimal.mark" =
ifelse(.Platform$OS.type == "windows", special_char$interpunct, "\U00B7"),
"style_number-arg:big.mark" = "\U2009",
"pkgwide-str:ci.sep" = " to ",
"tbl_summary-fn:addnl-fn-to-run" = function(x) {
x$table_styling$footnote_header$footnote <-
gsub("Q1 \U2013 Q3", "IQR", x = x$table_styling$footnote_header$footnote)
x
}
)
} else if (journal == "qjecon") {
lst_theme <-
list(
"pkgwide-str:theme_name" = "The Quarterly Journal of Economics",
"tbl_regression-arg:conf.int" = FALSE,
"tbl_summary-fn:percent_fun" = label_style_number(digits = 1, scale = 100),
"tbl_regression-fn:addnl-fn-to-run" = function(x) {
new_header_text <-
paste(
x$table_styling$header |> dplyr::filter(.data$column == "estimate") |> dplyr::pull("label"),
"**(SE)**",
sep = " \n"
)
x |>
add_significance_stars(
pattern = "{estimate}{stars} \n({std.error})",
hide_se = TRUE
) |>
# update column header
modify_header(estimate = new_header_text)
},
"as_gt-lst:addl_cmds" = list(
tab_spanner = list(
rlang::expr(gt::tab_style(style = "vertical-align:top", locations = gt::cells_body(columns = dplyr::any_of("label"))))
)
)
)
}
if (set_theme == TRUE) set_gtsummary_theme(lst_theme)
return(invisible(lst_theme))
}
# ------------------------------------------------------------------------------
#' @rdname theme_gtsummary
#' @export
theme_gtsummary_compact <- function(set_theme = TRUE, font_size = NULL) {
lst_theme <-
list(
"pkgwide-str:theme_name" = "Compact",
# compact gt tables
"as_gt-lst:addl_cmds" = list(
tab_spanner = rlang::expr(
gt::tab_options(
table.font.size = !!(font_size %||% 13),
data_row.padding = gt::px(1),
summary_row.padding = gt::px(1),
grand_summary_row.padding = gt::px(1),
footnotes.padding = gt::px(1),
source_notes.padding = gt::px(1),
row_group.padding = gt::px(1)
)
)
),
# compact flextables
"as_flex_table-lst:addl_cmds" = list(
valign = list(
rlang::expr(flextable::fontsize(size = !!(font_size %||% 8), part = "all")),
rlang::expr(flextable::padding(padding.top = 0, part = "all")),
rlang::expr(flextable::padding(padding.bottom = 0, part = "all")),
rlang::expr(flextable::set_table_properties(layout = "autofit"))
)
),
# compact huxtable
"as_hux_table.gtsummary-lst:addl_cmds" = list(
insert_row = list(
rlang::expr(huxtable::set_font_size(value = !!(font_size %||% 8))),
rlang::expr(huxtable::set_bottom_padding(value = 0)),
rlang::expr(huxtable::set_top_padding(value = 0))
)
),
# compact kableExtra
"as_kable_extra-lst:addl_cmds" = list(
kable = list(
rlang::expr(kableExtra::kable_styling(font_size = !!(font_size %||% 8)))
)
)
)
if (set_theme == TRUE) set_gtsummary_theme(lst_theme)
return(invisible(lst_theme))
}
# ------------------------------------------------------------------------------
#' @rdname theme_gtsummary
#' @param print_engine String indicating the print method. Must be one of
#' `"gt"`, `"kable"`, `"kable_extra"`, `"flextable"`, `"tibble"`
#' @export
theme_gtsummary_printer <- function(print_engine = c("gt", "kable", "kable_extra", "flextable", "huxtable", "tibble"),
set_theme = TRUE) {
lst_theme <- list("pkgwide-str:print_engine" = arg_match(print_engine))
if (set_theme == TRUE) set_gtsummary_theme(lst_theme)
return(invisible(lst_theme))
}
# ------------------------------------------------------------------------------
#' @rdname theme_gtsummary
#' @param language (`string`)\cr
#' String indicating language. Must be one of `"de"` (German),
#' `"en"` (English), `"es"` (Spanish), `"fr"` (French), `"gu"` (Gujarati),
#' `"hi"` (Hindi), `"is"` (Icelandic),`"ja"` (Japanese), `"kr"` (Korean),
#' `"nl"` (Dutch), `"mr"` (Marathi), `"no"` (Norwegian), `"pt"` (Portuguese),
#' `"se"` (Swedish), `"zh-cn"` (Chinese Simplified), `"zh-tw"` (Chinese Traditional),
#' `"ba"` (Bosnian)
#'
#' If a language is missing a translation for a word or phrase, please feel free
#' to reach out on [GitHub](https://github.com/ddsjoberg/gtsummary/issues)
#' with the translated text.
#' @param iqr.sep (`string`)\cr
#' String indicating separator for the default IQR in `tbl_summary()`.
#' If `decimal.mark=` is NULL, `iqr.sep=` is `", "`. The comma
#' separator, however, can look odd when `decimal.mark = ","`. In this case the argument
#' will default to an en dash
#' @param ci.sep (`string`)\cr
#' String indicating separator for confidence intervals.
#' If `decimal.mark=` is NULL, `ci.sep=` is `", "`. The comma
#' separator, however, can look odd when `decimal.mark = ","`. In this case the argument
#' will default to an en dash
#' @inheritParams style_number
#' @export
theme_gtsummary_language <- function(language = c(
"de", "en", "es", "fr", "gu", "hi", "is", "ja",
"kr", "mr", "nl", "no", "pt", "se", "zh-cn", "zh-tw", "ba"),
decimal.mark = NULL, big.mark = NULL,
iqr.sep = NULL,
ci.sep = NULL,
set_theme = TRUE) {
language <- match.arg(language)
ret <- list(
"pkgwide-str:theme_name" = paste("language:", language),
"pkgwide-str:language" = language
)
# setting formatting of numbers
if (!is.null(decimal.mark)) ret <- c(ret, list("style_number-arg:decimal.mark" = decimal.mark))
if (!is.null(big.mark)) ret <- c(ret, list("style_number-arg:big.mark" = big.mark))
# setting themes for separators
if (is.null(iqr.sep) && identical(decimal.mark, ",")) {
iqr.sep <- " \U2013 "
}
if (!is.null(iqr.sep)) {
ret <- c(ret,
list("tbl_summary-arg:statistic" =
list(all_continuous() ~ paste0("{median} ({p25}", iqr.sep, "{p75})"),
all_categorical() ~ "{n} ({p}%)"))
)
}
if (is.null(ci.sep) && identical(decimal.mark, ",")) {
ci.sep <- " \U2013 "
}
if (!is.null(ci.sep)) ret <- c(ret, list("pkgwide-str:ci.sep" = ci.sep))
# either returning list OR setting theme and returning list
if (set_theme == TRUE) set_gtsummary_theme(ret)
return(invisible(ret))
}
# ------------------------------------------------------------------------------
#' @rdname theme_gtsummary
#' @param statistic Default statistic continuous variables
#' @export
theme_gtsummary_continuous2 <- function(statistic = "{median} ({p25}, {p75})", set_theme = TRUE) {
lst_theme <- list(
"tbl_summary-str:default_con_type" = "continuous2",
"tbl_summary-arg:statistic" = list(all_continuous() ~ statistic, all_categorical() ~ "{n} ({p}%)")
)
if (set_theme == TRUE) set_gtsummary_theme(lst_theme)
return(invisible(lst_theme))
}
# ------------------------------------------------------------------------------
#' @rdname theme_gtsummary
#' @param statistic Default statistic continuous variables
#' @export
theme_gtsummary_mean_sd <- function(set_theme = TRUE) {
lst_theme <- list(
"tbl_summary-arg:statistic" = list(all_continuous() ~ "{mean} ({sd})", all_categorical() ~ "{n} ({p}%)"),
"add_p.tbl_summary-attr:test.continuous_by2" = "t.test",
"add_p.tbl_summary-attr:test.continuous" = "oneway.test",
"add_p.tbl_svysummary-attr:test.continuous" = "svy.t.test"
)
if (set_theme == TRUE) set_gtsummary_theme(lst_theme)
return(invisible(lst_theme))
}
# ------------------------------------------------------------------------------
#' @rdname theme_gtsummary
#' @export
theme_gtsummary_eda <- function(set_theme = TRUE) {
lst_theme <- list(
"pkgwide-str:theme_name" = "Exploratory Data Analysis",
"tbl_summary-str:default_con_type" = "continuous2",
"tbl_summary-arg:statistic" =
list(all_continuous() ~ c("{median} ({p25}, {p75})", "{mean} ({sd})", "{min}, {max}"),
all_categorical() ~ "{n} ({p}%)"),
"tbl_summary-fn:percent_fun" = label_style_percent(digits = 1)
)
if (set_theme == TRUE) set_gtsummary_theme(lst_theme)
return(invisible(lst_theme))
}