Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with 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, 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

like image 455
guna Avatar asked Jan 29 '23 21:01

guna


1 Answers

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
like image 97
akrun Avatar answered Feb 01 '23 08:02

akrun