0

I am creating a function with an optional input and its default value is NULL. I create logic within the function with an if statement - so if the input is not null do some action. However, I run into an issue with rlang::ensym() it does not seem to accept unquote strings as an argument within the if statement. If I remove the if statement and make the argument required both the quoted and unquote strings work. I am using rlang v1.1.0. How can I get the the function to accept unquoted inputs within the if statement? Here is a minimal example:

library(rlang)

f1 <- function(v2 = NULL){
  if(!is.null(v2)){
    v2 <- rlang::ensym(v2)
    dplyr::select(mtcars, !!v2)
  }
}

f1( v2 = "mpg") #works
f1( v2 = mpg) #error


f2 <- function(v2 ){
    v2 <- rlang::ensym(v2)
    dplyr::select(mtcars, !!v2)
}

f2( v2 = "mpg")#works
f2( v2 = mpg)#works
Mike
  • 3,797
  • 1
  • 11
  • 30
  • 1
    The `is.null()` call forces evaluation so you can't capture lazy parameters any more. you need to capture the symbol then use `rlang::quo_is_null`. For example `f1 <- function(v2 = NULL){v2 <- rlang::enquo(v2); if(!rlang::quo_is_null(v2)){v2 <- rlang::ensym(v2); dplyr::select(mtcars, !!v2)}}` – MrFlick Aug 04 '23 at 13:46

0 Answers0