Skip to content

Commit 917dabd

Browse files
committed
Write helper function for computed variables
1 parent b88f7b2 commit 917dabd

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

R/utilities-help.r

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,57 @@ rd_orientation <- function() {
4949
)
5050
)
5151
}
52+
53+
#' Format 'Computed variables' section
54+
#'
55+
#' This is a helper function that helps format the 'Computed variables' section
56+
#' of stat documentation pages. Briefly, it points to the delayed evaluation
57+
#' documentation and it wraps the variable names in
58+
#' 'after_stat()'.
59+
#'
60+
#' @param ... Named variable - description pairs. Variable names get wrapped in
61+
#' `after_stat()`. Variable names may be of the form "x|y" or "x,y" to format
62+
#' as "`after_stat(x)` or `after_stat(y)`" and
63+
#' "`after_stat(x)`, `after_stat(y)`" respectively.
64+
#' @param .details Additional details to include in the preamble.
65+
#' @param .skip_intro A logical, which if `TRUE` omits the link to the delayed
66+
#' evaluation docs. Can be useful when documenting two stat functions on the
67+
#' same page with different arguments, but no need to repeat the introduction
68+
#' in the second stat function (see e.g. `?stat_qq`).
69+
#'
70+
#' @return Formatted code that can be inserted into a .rd file.
71+
#' @keywords internal
72+
#' @noRd
73+
#' @examples
74+
#' rd_computed_vars(
75+
#' .details = "`stat_foobar()` computes the following variables:",
76+
#' "foo|bar" = "foobar",
77+
#' "bar,qux" = "quux",
78+
#' corge = "grault"
79+
#' )
80+
rd_computed_vars <- function(..., .details = "", .skip_intro = FALSE) {
81+
args <- list(...)
82+
items <- names(args)
83+
descr <- unname(args)
84+
85+
# Format preamble
86+
header <- "@section Computed variables: "
87+
intro <- paste0(
88+
"These are calculated by the 'stat' part of layers and can be accessed ",
89+
"with \\link[=aes_eval]{delayed evaluation}. "
90+
)
91+
if (.skip_intro) intro <- ""
92+
preamble <- c(header, paste0(intro, gsub("\n", "", .details)))
93+
94+
# Format items
95+
fmt_items <- gsub(",", ")}, \\code{after_stat(", items, fixed = TRUE)
96+
fmt_items <- gsub("|", ")} \\emph{or} \\code{after_stat(",
97+
fmt_items, fixed = TRUE)
98+
fmt_items <- paste0("\\item{\\code{after_stat(", fmt_items, ")}")
99+
100+
# Compose item-list
101+
fmt_descr <- paste0(gsub("\n", "", descr), "}")
102+
fmt_list <- paste(fmt_items, fmt_descr, sep = "\\cr ")
103+
104+
c(preamble, "\\itemize{", fmt_list, "}")
105+
}

0 commit comments

Comments
 (0)