The Chapter 19 of Advanced R explains that expr() is not useful inside the function.
However, in the following case, I could not make a function work without expr().
Let's suppose I want to group a tibble in a function.
data(iris)
iris %>% group_by(Species)
The obvious approach is to use "curly curly".
func_a <- function(data, grouping) {
data %>% group_by({{grouping}})
}
func_a(iris, Species)
However, "curly curly" does not work if I allow an arbitrarily supplied expressions.
func_b <- function(data, ...) {
data %>% group_by({{...}})
}
func_b(iris, Species)
# Error in (function (x) : object 'Species' not found
In the end, I found I need to expr() to make it work.
func_c <- function(data, ...) {
grouping <- expr(...)
data %>% group_by(!!grouping)
}
func_c(iris, Species)
The example of expr() in Advanced R is:
f1 <- function(x) expr(x)
f1(a + b + c)
#> x
My main question is why func_c works. Does expr() take ... as it is and evaluate it with !!? Why we have to take a different approach for ...?
Then, I am not sure why this does not work.
func_d <- function(data, grouping) {
grouping <- expr(grouping)
data %>% group_by(!!grouping)
}
func_d(iris, Species)
I also checked rlang manual, but the explanation is too brief for me.