Skip to content

Instantly share code, notes, and snippets.

@yutannihilation
Last active January 29, 2020 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yutannihilation/f30f837d06c07414d1a17ec148fb686b to your computer and use it in GitHub Desktop.
Save yutannihilation/f30f837d06c07414d1a17ec148fb686b to your computer and use it in GitHub Desktop.
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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment