How do {{}} double curly brackets work in dplyr?
Asked Answered
W

1

28

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?

Wizardry answered 25/9, 2020 at 13:21 Comment(0)
B
40

{{}} (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:

Blockbuster answered 25/9, 2020 at 13:33 Comment(7)
Ronak, so the {{}} is used to replace the enquo() and !! operators? i.e. does curly-curly performs both quote and unquote simultaneously ?Hew
Yes, exactly. It performs both the operations together.Blockbuster
How would this work if what is being enclosed in {{}} is a group of variables (e.g. in group_by) rather than just one?Diactinic
Hi. What is the purpose of using ':=' here rather than '='?Ushas
This is explained here. Basically the left hand side of = can't be an expression so you need to use := instead.Yemen
Is there a way to take advantage of this in ggplot2? It doesn't seem to work in an aes statement.Seagraves
ggplot2.tidyverse.org/dev/articles/…Sterilize

© 2022 - 2025 — McMap. All rights reserved.