Search code examples
rrlangquasiquotes

Passing on missing quasiquotation arguments


I am trying to use the quasiquotation to pass a raw variable name to a function, that passes it on to another function. However, the argument is optional, so I need to test if the 1st function was not given the argument and passed on that missing argument to the 2nd function.

In these examples b refers to a variable in a data.frame.

Testing if a function was passed a raw variable expression or no argument, I do

foo <- function(a) {
  print(is_missing(enexpr(a)))
}
foo()
# [1] TRUE
foo(b)
# [1] FALSE

Without the enexpr, the variable b will attempt to be evaluated - and when missing - Errors.

Next, I try to pass the missing argument to another function (bar) whom then will test for its presence:

foo2 <- function(a) {
  print(is_missing(enexpr(a)))
  bar(maybe_missing(a))
}
bar <- function(a) {
  print(is_missing(enexpr(a)))
}
foo2()
# [1] TRUE 
# [1] FALSE  <-- "wrong" (but not unexpected)
foo2(b)
# [1] FALSE
# [1] FALSE

Question: How can I in bar test whether foo2 was passed an argument?

Running R 3.5.1 with rlang 0.3.0.1.


Solution

  • We could do a !! and an enexpr in foo2

    foo2 <- function(a) {
      print(is_missing(enexpr(a)))
      bar(!!maybe_missing(enexpr(a)))
    }
    
    foo2()
    #[1] TRUE
    #[1] TRUE
    
    foo2(b)
    #[1] FALSE
    #[1] FALSE