I want to have a flexible function using summarize
in which:
- the aggregation function is given by user
- the aggregation function might use further arguments which refer to variables within the data itself.
A good example is the user providing fun=weighted.mean()
and specifying the weight argument w
.
For now, I am trying with the ...
. The problem is that I don't find a way to have that ...
refer to a variable within the data-frame? The example below is given using across()
, but the same happens if I use instead summarize_at()
Thanks!!
library(tidyverse)
fo1 <- function(df, fun=mean, ...){
df %>%
group_by(Species) %>%
summarise(across(starts_with("sepal"), fun, ...))
}
fo1(iris)
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 3 x 3
#> Species Sepal.Length Sepal.Width
#> <fct> <dbl> <dbl>
#> 1 setosa 5.01 3.43
#> 2 versicolor 5.94 2.77
#> 3 virginica 6.59 2.97
fo1(iris, fun=weighted.mean)
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 3 x 3
#> Species Sepal.Length Sepal.Width
#> <fct> <dbl> <dbl>
#> 1 setosa 5.01 3.43
#> 2 versicolor 5.94 2.77
#> 3 virginica 6.59 2.97
fo1(iris, fun=weighted.mean, w=Petal.Length)
#> Error: Problem with `summarise()` input `..1`.
#> x object 'Petal.Length' not found
#> ℹ Input `..1` is `across(starts_with("sepal"), fun, ...)`.
#> ℹ The error occurred in group 1: Species = "setosa".
fo1(iris, fun=weighted.mean, w=.data$Petal.Length)
#> Error: Problem with `summarise()` input `..1`.
#> x 'x' and 'w' must have the same length
#> ℹ Input `..1` is `across(starts_with("sepal"), fun, ...)`.
#> ℹ The error occurred in group 1: Species = "setosa".
Created on 2020-11-10 by the reprex package (v0.3.0)