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?
The curly brackets are used to denote a block of code in a function. So, say we need a function to calculate the standard error we might do this. The square brackets are used to subset vectors and data frames.
Brackets are used to insert explanations, corrections, clarifications, or comments into quoted material. Brackets are always used in pairs; you must have both an opening and a closing bracket.
Declare a template in the HTML file. Handlebars expressions are put into double curly braces {{expr}} for HTML-escaped content; otherwise, use triple curly brackets {{{expr}}} to avoid HTML-escaping.
The end of the variable name is usually signified by a space or newline. But what if we don't want a space or newline after printing the variable value? The curly braces tell the shell interpreter where the end of the variable name is.
{{}}
(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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With