25.11 Tidy evaluation and embracing

  • Tidy evaluation makes our data analyses very concise as you never have to say which data frame a variable comes from, but the downside comes when we want to wrap up repeated tidyverse code into a function.
  • Our solution to overcome to this problem called embracing 🤗. Embracing a variable means to wrap it in braces so (e.g.) var becomes {{ var }}.
grouped_mean <- function(df, group_var, mean_var) {
  df |> 
    group_by({{ group_var }}) |> 
    summarize(mean({{ mean_var }}))
}

df |>
  grouped_mean(group, x)
## # A tibble: 1 × 2
##   group `mean(x)`
##   <dbl>     <dbl>
## 1     1        10