library(dplyr, warn.conflicts = FALSE)
# c.f. https://github.com/r-lib/rlang/issues/906
quatro_curly <- function(data, what) {
data %>% summarise("{{ what }}" := mean({{ what }}))
}
quatro_curly(mtcars, mpg)
#> mpg
#> 1 20.09062
# fail
double_curly <- function(data, what) {
data %>% summarise("{what}" := mean({{ what }}))
}
double_curly(mtcars, mpg)
#> Error in eval(parse(text = text, keep.source = FALSE), envir): object 'mpg' not found
# fail
double_curly_quo <- function(data, what) {
what <- enquo(what)
data %>% summarise("{what}" := mean(!!what))
}
double_curly_quo(mtcars, mpg)
#> Warning: Using `as.character()` on a quosure is deprecated as of rlang 0.3.0.
#> Please use `as_label()` or `as_name()` instead.
#> This warning is displayed once per session.
#> Error: The LHS of `:=` must be a string or a symbol
# ok
double_curly_expr <- function(data, what) {
what <- enexpr(what)
data %>% summarise("{what}" := mean(!!what))
}
# symbol is ok
double_curly_expr(mtcars, mpg)
#> mpg
#> 1 20.09062
# expression fails
double_curly_expr(mtcars, sqrt(mpg))
#> Error: The LHS of `:=` must be a string or a symbol
# ok
quatro_curly_quo <- function(data, what) {
what <- enquo(what)
data %>% summarise("{{ what }}" := mean(!!what))
}
quatro_curly_quo(mtcars, mpg)
#> mpg
#> 1 20.09062
quatro_curly_quo(mtcars, sqrt(mpg))
#> sqrt(mpg)
#> 1 4.43477
Created on 2020-01-29 by the reprex package (v0.3.0)