Skip to content

Commit eaeee6d

Browse files
committed
add piece about character-based optional arguments
1 parent 1098b9e commit eaeee6d

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

vignettes/ggplot2-in-packages.Rmd

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,26 @@ col_summary <- function(df, col, by) {
105105
col_summary(mpg, "drv", "year")
106106
```
107107

108+
When using this strategy, you may need some extra care in passing optional arguments.
109+
You can use optional arguments by setting `NULL` as a default value, and treating non-null input with `rlang::data_syms`.
110+
Thereafter, these arguments can be spliced using the `!!!` operation.
111+
112+
```{r}
113+
col_summary <- function(df, col, by = NULL, fill = NULL, ...) {
114+
115+
optional <- list(fill = fill, ...)
116+
is_symbol <- lengths(optional) > 0
117+
optional <- c(data_syms(optional[is_symbol]), optional[!is_symbol])
118+
119+
by <- if (!is.null(by)) facet_wrap(vars(.data[[by]]))
120+
121+
ggplot(df) +
122+
geom_bar(aes(y = .data[[col]], !!!optional)) +
123+
by
124+
}
125+
126+
col_summary(mpg, "drv", colour = "class")
127+
```
108128
### Non-standard evaluation
109129

110130
If the column name or expression is supplied by the user, you can also pass it to `aes()` or `vars()` using `{{ col }}`. This tidy eval operator captures the expression supplied by the user and forwards it to another tidy eval-enabled function such as `aes()` or `vars()`.

0 commit comments

Comments
 (0)