I'm making a function that should be able to handle multiple classes for its first argument: formulas, characters, tidy-selection, var names... The goal is then to use tidyselection with tidyselect::vars_select
, except with bare formulas.
The problem is that when I test the class of this argument, it will throw an error if the value is a name to be tidy-selected, since it will be considered as a not found object.
I found a workaround with tryCatch
, which enquotes the first argument if its evaluation fails (and thus if it doesn't exist in this scope).
library(rlang)
foo=function(.vars){
.vars2=tryCatch(.vars, error=function(e) enquo(.vars))
print(class(.vars2))
print(class(.vars))
}
foo(Species)
# [1] "quosure" "formula"
# Error in print(class(.vars)) : object 'Species' not found
# In addition: Warning message:
# In print(class(.vars)) : restarting interrupted promise evaluation
foo(~Species)
# [1] "formula"
# [1] "formula"
foo(1)
# [1] "numeric"
# [1] "numeric"
foo("Species")
# [1] "character"
# [1] "character"
This doesn't seem clean to me, as I'm catching all errors without filtering on my specific case.
Is there a built-in function to test this, or a cleaner solution than this workaround?
I think the following is what you are trying to do (using here only base R).