This is related to the question I had here: Getting 'argument “e2” is missing with no default' error when using tidyeval within dplyr::summarize_at
While the error response is now more helpful, it's still not yet clear to me how to use quosures within scoped variants of mutate()
and summarize()
.
Let's say I have the following data set:
library(tidyverse)
data <- tibble(
weighting = rnorm(10, 1, 0.1),
vara = rbinom(10, 1, 0.5),
varb = rbinom(10, 1, 0.5),
varc = rbinom(10, 1, 0.5)
)
And I have this function that I want to apply to it:
myfun <- function(df, weight) {
weight <- enquo(weight)
summarize_at(df, vars(starts_with("var")), funs(sum(if_else(. == 1, !! weight, 0)) / sum(!! weight)))
}
Before the full deprecation of funs()
this would work fine:
myfun(data, weighting)
# A tibble: 1 x 3
vara varb varc
<dbl> <dbl> <dbl>
0.710 0.284 0.523
However, how would I do this in the future? My best attempt is the following, but it returns an error:
myfun2 <- function(df, weight) {
weight <- enquo(weight)
summarize_at(df, vars(starts_with("var")), list(~sum(if_else(. == 1, !! weight, 0)) / sum(!! weight)))
}
myfun2(data, weighting)
Error: Quosures can only be unquoted within a quasiquotation context.
# Bad:
list(!!myquosure)
# Good:
dplyr::mutate(data, !!myquosure)
The error response tells me simply to not use the scoped variants, which is unhelpful to what I'm trying to do.