23

I saw Hadley's talk at RConf and he mentioned using double brackets for calling variables in tidy evals.

I searched Google but I couldn't find anything talking about when to use them.

What's the use case for double brackets in dplyr?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Cauder
  • 2,157
  • 4
  • 30
  • 69

1 Answers1

38

{{}} (curly-curly) have lot of applications. It is called as meta-programming and is used for writing functions. For example, consider this example :

library(dplyr)
library(rlang)

mtcars %>% group_by(cyl) %>% summarise(new_mpg = mean(mpg))

# A tibble: 3 x 2
#    cyl new_mpg
#  <dbl>   <dbl>
#1     4    26.7
#2     6    19.7
#3     8    15.1

Now if you want to write this as a function passing unquoted variables (not a string), you can use {{}} as :

my_fun <- function(data, group_col, col, new_col) {
  data %>%
    group_by({{group_col}}) %>%
    summarise({{new_col}} := mean({{col}}))
}

mtcars %>% my_fun(cyl, mpg, new_mpg)

#    cyl new_mpg
#  <dbl>   <dbl>
#1     4    26.7
#2     6    19.7
#3     8    15.1

Notice that you are passing all the variables without quotes and the group-column (cyl), the column which is being aggregated (mpg), the name of new column (new_mpg) are all dynamic. This would just be one use-case of it.

To learn more refer to:

zx8754
  • 52,746
  • 12
  • 114
  • 209
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 2
    Ronak, so the {{}} is used to replace the enquo() and !! operators? i.e. does curly-curly performs both quote and unquote simultaneously ? – Karthik S Sep 26 '20 at 09:34
  • 3
    Yes, exactly. It performs both the operations together. – Ronak Shah Sep 26 '20 at 09:42
  • 1
    How would this work if what is being enclosed in {{}} is a group of variables (e.g. in group_by) rather than just one? – user11151932 Jan 02 '21 at 04:56
  • 2
    Hi. What is the purpose of using ':=' here rather than '='? – D Greenwood Nov 05 '21 at 16:21
  • 2
    This is explained [here](https://adv-r.hadley.nz/quasiquotation.html#tidy-dots). Basically the left hand side of `=` can't be an expression so you need to use `:=` instead. – Dan Adams Feb 20 '22 at 01:41
  • Is there a way to take advantage of this in ggplot2? It doesn't seem to work in an `aes` statement. – Arthur Jun 04 '22 at 03:40
  • 1
    https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html#using-aes-and-vars-in-a-package-function – Desmond Jul 18 '22 at 08:27