Refer: http://dplyr.tidyverse.org/articles/programming.html
This Code works Fine:
df <- tibble(
  g1 = c(1, 1, 2, 2, 2),
  g2 = c(1, 2, 1, 2, 1),
  a = sample(5), 
  b = sample(5)
)
my_summarise <- function(df, group_by) {
  group_by <- enquo(group_by)
  print(group_by)
  df %>%
    group_by(!!group_by) %>%
    summarise(a = mean(a))
}
my_summarise(df, g1)
However, just if we wrap this function in another, and make the call, it will not work. Is it because the name gets passed only for one level?
wrapped_my_Summarize <- function(wdf, w_group_by){
  my_summarise(wdf, w_group_by)
}
wrapped_my_Summarize(df, g1)
In general, I feel the above example is a risky one to go with
Convert it to quosure from the symbol with enquo and then evaluate the function argument (!!) of my_summarise
wrapped_my_Summarize <- function(wdf, w_group_by){
  w_group_by <- enquo(w_group_by) 
  my_summarise(wdf, !! w_group_by)
}
wrapped_my_Summarize(df, g1)
# A tibble: 2 x 2
#     g1     a
#   <dbl> <dbl>
#1  1.00  2.00
#2  2.00  3.67
identical(wrapped_my_Summarize(df, g1), my_summarise(df, g1))
#[1] TRUE
                        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