I want to write a generalized weighted_summarise() function that will automatically parse and transform user-invoked function calls of the form:
data %>% weighted_summarise(weights, a = sum(b), c = mean(d))
into an actual call that delegates to dplyr::summarise
data %>% dplyr::summarise(a = sum(weights * b), c = mean(weights * d))
Here, a and c are new columns to be created inside the reduced data, and b, d and weights are existing columns in data.
Ideally, I want my to call my function exactly as I would a "native" dplyr::summarise, but with an extra weights argument that gets sprinkled into each aggregation function.
weighted_summarise <- function(data, weights, ...) {
data %>% dplyr::summarise(
# how to manipulate the ... and inject the weights in each name-value pair?
)
}
Question How can I manipulate the ellipsis so that the weights will be injected into every name-value pair in the appropriate place? I want to somehow capture an AST and walk it and manipulate it systematically.