Customize dplyr summarise function

Welcome to the community!

Try something like this:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

custom_summarise <- function(df, a)
{
    df %>%
        summarise(Mean = mean(x = {{a}}), 
                  SD = sd(x = {{a}}), 
                  `CV%` = (SD / Mean * 100))
}

iris %>% 
    group_by(Species) %>% 
    custom_summarise(a = Sepal.Length)
#> # A tibble: 3 x 4
#>   Species     Mean    SD `CV%`
#>   <fct>      <dbl> <dbl> <dbl>
#> 1 setosa      5.01 0.352  7.04
#> 2 versicolor  5.94 0.516  8.70
#> 3 virginica   6.59 0.636  9.65

Created on 2020-04-19 by the reprex package (v0.3.0)

You can take a look at this.

Hope this helps.


PS: To be frank, I always get confused (a lot) with {{, !!, !!! etc. Maybe someone more familiar with these may take a look at this thread and provide a link to a detailed documentation for both of us.

1 Like