How to use dplyr within a function?

4

Let's say I wanted to create a function that internally uses some functions of the or any that use this type of syntax.

By way of illustration:

exemplo <- function(df, predicado, sumario) {
  df %>% filter(predicado) %>% 
    summarise(sumario)
}

Ideally, this function should run like this:

exemplo(mtcars, cyl == 4, mean(wt))

But when I squeeze it, I get it.

  

Error in filter_impl (.data, quo): object 'cyl' not found

The expected result is the same as when we do

mtcars %>% filter(cyl == 4) %>% 
  summarise(mean(wt))

#   mean(wt)
# 1 2.285727

Then I ask you how to use the in the body of a function without giving up using the power and simplicity of its syntax?

    
asked by anonymous 29.06.2018 / 16:40

1 answer

4

dplyr has a nice syntax to program interactively, and the tradeoff of it is just programming when we are in functions.

The best place to understand how everything works is this vignette .

In your example, you could do this:

exemplo <- function(df, predicado, sumario) {
  predicado <- enquo(predicado)
  sumario <- enquo(sumario)

  df %>% 
    filter(!! predicado) %>% 
    summarise(!! sumario)
}

exemplo(mtcars, cyl == 4, mean(wt))

This function enquo saves the argument passed by the user to something like a string, which can then be used within the functions of dplyr preceded by !! .

    
03.07.2018 / 11:48