I am wrapping up the development of my first CRAN submission and ran into an issue with our use of non-standard evaluation.
The following is a simplified reprex that reproduces our issue. The function a()
works just fine if sourceVar
is unquoted in the initial call. However, it throws an error if sourceVar
is quoted.
suppressMessages(library(dplyr))
library(rlang)
testData <- data.frame(x = c(1, 2, 3, 4, 5))
a <- function(.data, sourceVar, cleanVar) {
# quote input
cleanVar <- quo_name(enquo(cleanVar))
sourceVar <- enquo(sourceVar)
# create new variable
mutate(.data, !!cleanVar := (!!sourceVar)*2)
}
a(testData, sourceVar = x, cleanVar = y)
#> x y
#> 1 1 2
#> 2 2 4
#> 3 3 6
#> 4 4 8
#> 5 5 10
a(testData, sourceVar = "x", cleanVar = y)
#> Error in mutate_impl(.data, dots): Evaluation error: non-numeric argument to binary operator.
What is curious to me is not just that this fails, but it only seems to matter on the right side of our mutate call. Regardless if we quote or unquote the input for cleanVar
, it successfully evaluates a()
:
suppressMessages(library(dplyr))
library(rlang)
testData <- data.frame(x = c(1, 2, 3, 4, 5))
b <- function(.data, sourceVar, cleanVar) {
# quote input
cleanVar <- quo_name(enquo(cleanVar))
sourceVar <- enquo(sourceVar)
# create new variable
mutate(.data, !!cleanVar := (!!sourceVar)*2)
}
b(testData, sourceVar = x, cleanVar = y)
#> x y
#> 1 1 2
#> 2 2 4
#> 3 3 6
#> 4 4 8
#> 5 5 10
b(testData, sourceVar = x, cleanVar = "y")
#> x y
#> 1 1 2
#> 2 2 4
#> 3 3 6
#> 4 4 8
#> 5 5 10
Any help schooling me on where I am going wrong here, or how we can flexibly accommodate quoted and unquoted inputs on the righthand side our of mutate calls, would be much appreciated!