This is a curiosity question---I'll never actually need to do this, but I'm trying to understand R's quasiquotation and tidy evaluation features and I think this will help me with that.
Suppose you want to filter the droids from the starwars
dataset:
library(dplyr)
library(rlang)
starwars %>% filter(species == "Droid")
Is it possible to do something like saving the filter
call, and reuse it later? This would be useful for conciseness if there were many conditions to filter by. Something like
filter_droid = some_quote(filter(species == "Droid"))
starwars %>% some_unquote(filter_droid)
Of course, you could do it this way:
cond = expr(species == "Droid")
starwars %>% filter(eval(cond))
but this idea doesn't always work when there are multiple arguments. For instance when making two new columns with mutate
, this doesn't work:
new_cols = exprs(col1 = 1, col2 = 2)
starwars %>% mutate(eval(new_cols))
If I were writing a script, I would fix this is by just defining a function that does the mutate
call for me---for the sake of curiosity I want to ignore doing that. How can you "save" the mutate
/filter
call, or at least the arguments inside them, to use later in your code interactively?