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