xiaodai
xiaodai

Reputation: 16014

How to use tidy eval NSE to expand a `an expression`

I want to expand the !!! expression just like they do in dplyr-verbs e.g.

aggregate_expressions <- list(n = quote(n()))

do_something(iris, !!!(aggregate_expressions))

and say I want do_something to perform

do_something <- function(...) {
  iris %>%
    some_function( # expand the ... # ) # some_function(n = n())
}

which will do this but the n = n() is dynamic

do_something <- function(...) {
  iris %>%
    some_function(n = n())
}

I tried to trace the code for dplyr::summarise and I see that enquos(...) which converts the ... to a list of quosure, but then how do I apply the quosures? I think I am meant to create the code summarise(n = n()) from the quosure and then evaluate i using eval_tidy, but I can't figure out how to generate the code. I know that pass ... summarise works but the actual use case is to pass it to summarise.disk.frame which means I can't just reuse dplyr::summarise

The actual case i not

For example in dplyr, the below works by expanding the aggregate_expression using !!!

  aggregate_expressions <- list(n = quote(n()))

  iris %>%    
    group_by(Species) %>%
    summarise(!!!(aggregate_expressions))

Upvotes: 0

Views: 73

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269664

Modify it like this:

do_something <- function(x) {
  iris %>%
    summarise(!!!x)
}

aggregate_expressions <- list(n = quote(n()))
do_something(aggregate_expressions)
##     n
## 1 150

Upvotes: 1

Related Questions