How do {{}} double curly brackets work in dplyr?

Viewed 4675

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?

1 Answers

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

Related