forked from ddsjoberg/gtsummary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modify.R
394 lines (353 loc) · 13.5 KB
/
modify.R
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
#' Modify column headers, footnotes, spanning headers, and table captions
#'
#' These functions assist with updating or adding column headers
#' (`modify_header()`), footnotes (`modify_footnote()`), spanning
#' headers (`modify_spanning_header()`), and table captions
#' (`modify_caption()`). Use `show_header_names()` to learn
#' the column names.
#'
#' @name modify
#' @param x a gtsummary object
#' @param update,... use these arguments to assign updates to headers,
#' spanning headers, and footnotes. See examples below.
#' - `update` expects a list of assignments, with the variable name or selector
#' on the LHS of the formula, and the updated string on the RHS. Also accepts
#' a named list.
#' - `...` pass individual updates outside of a list, e.g,
#' `modify_header(p.value = "**P**", all_stat_cols() ~ "**{level}**")`
#'
#' Use the `show_header_names()` to see the column names that can be modified.
#' @param abbreviation Logical indicating if an abbreviation is being updated.
#' @param stat_by DEPRECATED, use `update = all_stat_cols() ~ "<label>"` instead.
#' @param text_interpret String indicates whether text will be interpreted with
#' [gt::md()] or [gt::html()]. Must be `"md"` (default) or `"html"`.
#' @param caption a string of the table caption/title
#' @param include_example logical whether to include print of `modify_header()` example
#' @inheritParams modify_table_styling
#' @inheritParams add_global_p
#' @family tbl_summary tools
#' @family tbl_svysummary tools
#' @family tbl_regression tools
#' @family tbl_uvregression tools
#' @family tbl_survfit tools
#' @author Daniel D. Sjoberg
#'
#' @section tbl_summary(), tbl_svysummary(), and tbl_cross():
#' When assigning column headers, footnotes, spanning headers, and captions
#' for these gtsummary tables,
#' you may use `{N}` to insert the number of observations.
#' `tbl_svysummary` objects additionally have `{N_unweighted}` available.
#'
#' When there is a stratifying `by=` argument present, the following fields are
#' additionally available to stratifying columns: `{level}`, `{n}`, and `{p}`
#' (`{n_unweighted}` and `{p_unweighted}` for `tbl_svysummary` objects)
#'
#' Syntax follows [glue::glue()], e.g. `all_stat_cols() ~ "**{level}**, N = {n}"`.
#' @section tbl_regression():
#' When assigning column headers for `tbl_regression` tables,
#' you may use `{N}` to insert the number of observations, and `{N_event}`
#' for the number of events (when applicable).
#'
#' @section captions:
#' Captions are assigned based on output type.
#' - `gt::gt(caption=)`
#' - `flextable::set_caption(caption=)`
#' - `huxtable::set_caption(value=)`
#' - `knitr::kable(caption=)`
#'
#' @examples
#' \donttest{
#' # create summary table
#' tbl <- trial[c("age", "grade", "trt")] %>%
#' tbl_summary(by = trt, missing = "no") %>%
#' add_p()
#'
#' # print the column names that can be modified
#' show_header_names(tbl)
#'
#' # Example 1 ----------------------------------
#' # updating column headers, footnote, and table caption
#' modify_ex1 <- tbl %>%
#' modify_header(label = "**Variable**", p.value = "**P**") %>%
#' modify_footnote(all_stat_cols() ~ "median (IQR) for Age; n (%) for Grade") %>%
#' modify_caption("**Patient Characteristics** (N = {N})")
#'
#' # Example 2 ----------------------------------
#' # updating headers, remove all footnotes, add spanning header
#' modify_ex2 <- tbl %>%
#' modify_header(all_stat_cols() ~ "**{level}**, N = {n} ({style_percent(p)}%)") %>%
#' # use `modify_footnote(everything() ~ NA, abbreviation = TRUE)` to delete abbrev. footnotes
#' modify_footnote(update = everything() ~ NA) %>%
#' modify_spanning_header(all_stat_cols() ~ "**Treatment Received**")
#'
#' # Example 3 ----------------------------------
#' # updating an abbreviation in table footnote
#' modify_ex3 <-
#' glm(response ~ age + grade, trial, family = binomial) %>%
#' tbl_regression(exponentiate = TRUE) %>%
#' modify_footnote(ci = "CI = Credible Interval", abbreviation = TRUE)
#' }
#' @return Updated gtsummary object
#' @section Example Output:
#' \if{html}{Example 1}
#'
#' \if{html}{\out{
#' `r man_create_image_tag(file = "modify_ex1.png", width = "45")`
#' }}
#'
#' \if{html}{Example 2}
#'
#' \if{html}{\out{
#' `r man_create_image_tag(file = "modify_ex2.png", width = "45")`
#' }}
#'
#' \if{html}{Example 3}
#'
#' \if{html}{\out{
#' `r man_create_image_tag(file = "modify_ex3.png", width = "35")`
#' }}
NULL
#' @name modify
#' @export
modify_header <- function(x, update = NULL, ..., text_interpret = c("md", "html"),
quiet = NULL, stat_by = NULL) {
updated_call_list <- c(x$call_list, list(modify_header = match.call()))
.assert_class(x, "gtsummary")
# setting defaults -----------------------------------------------------------
quiet <- quiet %||% get_theme_element("pkgwide-lgl:quiet") %||% FALSE
text_interpret <- match.arg(text_interpret)
# converting update and dots args to a tidyselect list -----------------------
if (!is.null(stat_by)) {
lifecycle::deprecate_stop(
"1.3.6", "gtsummary::modify_header(stat_by=)",
details = glue("Use `all_stat_cols(FALSE) ~ {stat_by}` instead.")
)
}
update <- .combine_update_and_dots(x, update, ...)
# if no columns selected, print helpful message
if (is.null(update) && identical(quiet, FALSE)) .modify_no_selected_vars(x)
if (is.null(update)) {
return(x)
}
# evaluating update with glue ------------------------------------------------
update <- .eval_with_glue(x, update)
# updating column headers ----------------------------------------------------
x <-
modify_table_styling(
x,
columns = names(update),
label = unlist(update),
text_interpret = as.character(text_interpret),
hide = FALSE
)
# returning gtsummary object -------------------------------------------------
x$call_list <- updated_call_list
x
}
#' @name modify
#' @export
modify_footnote <- function(x, update = NULL, ..., abbreviation = FALSE,
text_interpret = c("md", "html"), quiet = NULL) {
updated_call_list <- c(x$call_list, list(modify_footnote = match.call()))
# checking inputs ------------------------------------------------------------
.assert_class(x, "gtsummary")
# setting defaults -----------------------------------------------------------
quiet <- quiet %||% get_theme_element("pkgwide-lgl:quiet") %||% FALSE
# update table_styling -------------------------------------------------------
x <- .update_table_styling(x)
# converting update arg to a tidyselect list ---------------------------------
update <- .combine_update_and_dots(
x,
{
update
},
...
)
# if no columns selected, print helpful message
if (identical(quiet, FALSE) && rlang::is_empty(update)) .modify_no_selected_vars(x)
if (is.null(update)) {
return(x)
}
# evaluating update with glue ------------------------------------------------
update <- .eval_with_glue(x, update)
# updating footnotes ---------------------------------------------------------
modify_table_styling_args <- list(
x = x,
columns = names(update),
footnote = unlist(update),
text_interpret = text_interpret
)
if (isTRUE(abbreviation)) { # for abbreviations, update list names
modify_table_styling_args <-
stats::setNames(
modify_table_styling_args,
c("x", "columns", "footnote_abbrev", "text_interpret")
)
}
x <- do.call(modify_table_styling, modify_table_styling_args)
# returning gtsummary object -------------------------------------------------
x$call_list <- updated_call_list
x
}
#' @name modify
#' @export
modify_spanning_header <- function(x, update = NULL, ...,
text_interpret = c("md", "html"), quiet = NULL) {
updated_call_list <- c(x$call_list, list(modify_spanning_header = match.call()))
# checking inputs ------------------------------------------------------------
.assert_class(x, "gtsummary")
# setting defaults -----------------------------------------------------------
quiet <- quiet %||% get_theme_element("pkgwide-lgl:quiet") %||% FALSE
# update table_styling --------------------------------------------------------
x <- .update_table_styling(x)
# converting update arg to a tidyselect list ---------------------------------
update <- .combine_update_and_dots(
x,
{
update
},
...
)
# if no columns selected, print helpful message
if (identical(quiet, FALSE) && rlang::is_empty(update)) .modify_no_selected_vars(x)
if (is.null(update)) {
return(x)
}
# evaluating update with glue ------------------------------------------------
update <- .eval_with_glue(x, update)
# updating spanning header ---------------------------------------------------
x <-
modify_table_styling(
x,
columns = names(update),
spanning_header = unlist(update),
text_interpret = text_interpret
)
# return updated gtsummary object --------------------------------------------
x$call_list <- updated_call_list
x
}
#' @name modify
#' @export
modify_caption <- function(x, caption, text_interpret = c("md", "html")) {
# checking inputs ------------------------------------------------------------
.assert_class(x, "gtsummary")
if (!rlang::is_string(caption)) abort("`caption=` must be a string.")
text_interpret <- match.arg(text_interpret)
updated_call_list <- c(x$call_list, list(modify_caption = match.call()))
# evaluating update with glue ------------------------------------------------
if ("label" %in% x$table_styling$header$column) {
caption <- # eval on the label column stats
.eval_with_glue(x, list(label = caption)) %>%
unlist() %>%
unname()
}
# adding caption to gtsummary object ----------------------------------------
x$table_styling$caption <- caption
attr(x$table_styling$caption, "text_interpret") <- text_interpret
# returning updated object ---------------------------------------------------
x$call_list <- updated_call_list
x
}
#' @name modify
#' @export
show_header_names <- function(x = NULL, include_example = TRUE, quiet = NULL) {
# setting defaults -----------------------------------------------------------
quiet <- quiet %||% get_theme_element("pkgwide-lgl:quiet") %||% FALSE
# checking input -------------------------------------------------------------
.assert_class(x, "gtsummary")
df_cols <-
x$table_styling$header %>%
filter(.data$hide == FALSE) %>%
select("column", "label")
if (identical(quiet, FALSE) && isTRUE(include_example)) {
cat("\n")
cli_alert_info("As a usage guide, the code below re-creates the current column headers.")
block <- mutate(df_cols, formula = glue(" {column} = {shQuote(label)}")) %>%
pull("formula") %>%
paste0("", collapse = ",\n") %>%
{
glue("modify_header(\n{.}\n)")
}
cli_code(block)
}
if (identical(quiet, FALSE)) {
knitr::kable(df_cols, col.names = c("Column Name", "Column Header"), format = "pandoc") %>%
print()
}
return(invisible(df_cols))
}
# prints a helpful message when no columns were selected in the modify functions
.modify_no_selected_vars <- function(x) {
paste(
"No columns were selected.",
"Use {.code quiet = TRUE} to supress these messages."
) %>%
stringr::str_wrap() %>%
cli_alert_info()
show_header_names(x)
}
.combine_update_and_dots <- function(x, update, ...) {
dots <- rlang::dots_list(...)
if (!is.null(update) && !rlang::is_list(update)) {
update <- list(update)
}
.formula_list_to_named_list(
x = c(update, dots),
data = x$table_body,
var_info =
x$table_styling$header %>%
select("column", "hide", starts_with("modify_selector_")) %>%
dplyr::rename_with(
.fn = ~ stringr::str_remove(., pattern = fixed("modify_selector_")),
starts_with("modify_selector_")
),
arg_name = "... or update",
type_check = chuck(type_check, "is_string_or_na", "fn"),
type_check_msg = chuck(type_check, "is_string_or_na", "msg")
)
}
.eval_with_glue <- function(x, update) {
df_header <-
x$table_styling$header %>%
select("column", starts_with("modify_stat_")) %>%
dplyr::rename_with(~ stringr::str_replace(., fixed("modify_stat_"), fixed("")))
imap(
update,
function(x, y) {
if (!y %in% df_header$column) {
cli::cli_alert_warning("Column {.val {y}} not found and was ignored.")
return(NULL)
}
lst_env_for_eval <-
df_header %>%
filter(.data$column %in% .env$y) %>%
as.list() %>%
discard(is.na)
tryCatch(
expr(ifelse(!is.na(!!x), glue(!!x), NA_character_)) %>%
eval_tidy(data = lst_env_for_eval),
error = function(e) {
# if string has open and close {}, then print detailed message
if (!is_empty(lst_env_for_eval) && stringr::str_detect(x, pattern = "\\{*\\}")) {
tryCatch(
{
cls <-
imap(lst_env_for_eval, ~ glue("{{.field {.y}}} ({{.cls {class(.x)[1]}}})")) %>%
paste(collapse = ", ")
cli::cli_alert_danger(
"There was an error processing column {.val {y}}--likely a glue syntax error."
)
paste("The following fields are available to insert via glue syntax:\n", cls) %>%
cli::cli_alert_info()
},
error = function(e) invisible()
)
}
glue("Error processing `modify_*()` for column '{y}'.") %>% stop(call. = FALSE)
}
)
}
) %>%
purrr::compact()
}