I have a function that includes an optional variable parameter. By default, I set the variable to NULL
, but if it isn't NULL
I'd like my function to do some stuff. I need a way to check if the variable is not null. This is complicated because I am using tidyeval, and just using is.null(var)
throws an object not found error. I've found a hacky solution using try
, but am hoping there's a better way.
library(dplyr)
dat <- data.frame(value = 1:8,
char1 = c(rep("a", 4), rep("b", 4)),
char2 = rep(c(rep("c", 2), rep("d", 2)), 2))
myfun <- function(dat, group = NULL, var = NULL) {
x <- dat %>%
group_by({{group}}, {{var}}) %>%
summarize(mean = mean(value),
.groups = "drop")
# if(!is.null(var)) { # Throws object not found error if not null
null_var <- try(is.null(var), silent = TRUE)
null_var <- null_var == TRUE
if(!null_var) {
print("do something with `var`")
}
x
}
myfun(dat)
myfun(dat, char1)
myfun(dat, char1, char2)
{{
is the combination of enquo()
and !!
in one step. To inspect the contents of var
, you need to decompose these two steps. enquo()
defuses the argument and returns a quosure that you can inspect. !!
injects the quosure into other calls.
Below we enquo()
the argument at the start of the function. Inspect it with quo_is_null()
(you could also use quo_get_expr()
to see what's inside it). Then inject it inside group_by()
with !!
:
myfun <- function(dat, group = NULL, var = NULL) {
var <- enquo(var)
if (!quo_is_null(var)) {
print("It works!")
}
# Use `!!` instead of `{{` because we have decomposed the
# `enquo()` and `!!` steps that `{{` bundles
dat %>%
group_by({{ group }}, !!var) %>%
summarize(mean = mean(value), .groups = "drop")
}