I editing an existing function in a package. Currently, the function accepts a column name in a data frame as a string. I am updating the function to accept either a string name or a bare name. But I am running into some issues.
The general approach I'd like to take is to convert a bare to a string, so the rest of the function does not need to be updated. If the user passes a string column name, then I don't need to modify the input.
The code below converts a bare input to a string, but I can't figure out how to conditionally convert to a string or leave the string unmodified.
test_fun <- function(by) {
# convert to enquo
by1 <- rlang::enquo(by)
# convert enquo to string
by2 <- rlang::quo_text(by1)
by2
}
# converts to string
test_fun(varname)
# not sure how to pass this unmodified
test_fun("varname")
As noted, I strongly recommend against the practice of accepting multiple types if this creates ambiguity (and it does, here).
That said, the following does it:
test_fun = function (by) {
by = substitute(by)
if (is.name(by)) {
as.character(by)
} else if (is.character(by)) {
by
} else {
stop('Unexpected type')
}
}
Using rlang, in this case, doesn’t simplify the code.