I have a function which creates dataframe, but changes names in the process. I am trying to handle empty column names with dplyr quosures. My test suite looks like this:
This problem doesn't really have to do with quo
and enquo
returning different things, it's really about evaluating objects before you really want to. If you were to use the browser()
to step through your function, you'd see the error occurs at the if (is.null(new_var_name))
statement.
When you do is.null(new_var_name)
, you are evaluating the variable passed as new_var_name
so it's too late to enquo
it. That's because is.null
needs to look at the value of the variable rather than just the variable name itself.
A function that does not evaluate the parameter passed to the function but checks to see if it is there is missing()
.
my_fun <- function(df, col_name, new_var_name=NULL) {
target <- enquo(col_name)
c <- df %>% pull(!!target) * 3 # here may be more complex calculations
# handling NULL name
if (missing(new_var_name)) {
new_name <- "default_name"
} else{
new_name <- quo_name(enquo(new_var_name))
}
data_frame(
abc = df %>% pull(!!target),
!!new_name := c
)
}
Then you can run both of these
my_fun(dataframe, a)
my_fun(dataframe, a, NEW_NAME)