Problem with an example in: Programming with dplyr

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, if we wrap this function in another and make a call, it will not work. Is it because the name is passed only for one level?

wrapped_my_Summarize <- function(wdf, w_group_by){
  my_summarise(wdf, w_group_by)
}

wrapped_my_Summarize(df, g1)

All in all, I feel like the above example is risky to go with

+4
source share
1 answer

Convert it to quosure from character with enquo, and then evaluate the function argument ( !!)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
+8
source

Source: https://habr.com/ru/post/1691961/


All Articles