3

I have a list of quosures in my_q_list below:

library(rlang)
suppressPackageStartupMessages(library(dplyr))

q_list <- function(...) {
  enquos(...)
}

my_q_list <- q_list(
  select(mpg, hp),
  filter(hp > 20),
  mutate(mpg2 = mpg*2)
)

my_q_list
#> <list_of<quosure>>
#> 
#> [[1]]
#> <quosure>
#> expr: ^select(mpg, hp)
#> env:  global
#> 
#> [[2]]
#> <quosure>
#> expr: ^filter(hp > 20)
#> env:  global
#> 
#> [[3]]
#> <quosure>
#> expr: ^mutate(mpg2 = mpg * 2)
#> env:  global

Created on 2020-07-01 by the reprex package (v0.3.0)

Using rlang and purrr, how do I pipe the mtcars dataset into this list and evaluate each expression, returning a list of three data frames?

David Ranzolin
  • 913
  • 1
  • 6
  • 18

1 Answers1

3

One approach is to use quosure arithmetic:

purrr::map( my_q_list, ~quo( mtcars %>% !!.x ) ) %>%       # Construct desired quosures
    purrr::map( quo_squash ) %>%                           # Simplify them
    purrr::map( eval_tidy )                                # Evaluate them
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74