0

I want to use quoted arguments in my function and I would like to allow the user to specify that they don't want to use the argument by setting it to NULL. However, rlang::ensym throws an error when it receives a NULL argument. Here is my code:

f <- function(var){
  rlang::ensym(var)
  return(var + 2)
}

# This works
variable = 2
f(variable)
# This throws an error
f(NULL)

The error message is:

Error: Only strings can be converted to symbols

I already tried adding an if-clause with is.null(var) before the expression with rlang::ensym, but of course, this doesn't work as the variable is not yet quoted at this time.

How can I check that the supplied quoted variable is NULL in order to handle it differently?

MrFlick
  • 195,160
  • 17
  • 277
  • 295
Lukas D. Sauer
  • 355
  • 2
  • 11

1 Answers1

4

If you need to allow for NULL, it's more robust to use quosures first. Then you can inspect the quosure to see what's inside. For example

f <- function(var){
  var <- rlang::enquo(var)
  if (rlang::quo_is_null(var)) {
    var <- NULL
  } else if (rlang::quo_is_symbol(var)) {
    var <- rlang::get_expr(var)
  } else {
    stop(paste("Expected symbol but found", class(rlang::get_expr(var))))
  }
  return(var)
}

And that returns

f(variable)
# variable
f(NULL)
# NULL
f(x+1)
# Error in f(x + 1) : Expected symbol but found call

Or you can use whatever logic is appropriate for your actual requirements.

MrFlick
  • 195,160
  • 17
  • 277
  • 295