Closed tomasjanikds closed 3 years ago
You are able to pass an expression programmatically to aggregate_key()
using !!
. Here is an example of it in use:
library(tsibble)
library(fabletools)
spec <- "Purpose * (Region / State)"
spec_expr <- rlang::parse_expr(spec)
tourism %>%
aggregate_key(.spec = !!spec_expr, Trips = sum(Trips))
The rlang::parse_expr()
function is parsing the string into an expression, which is then provided in aggregate_key()
with !!
.
A few things to note,
rlang::parse_expr()
may not be the best (safest) way to create the expression. A better way is to construct the expression without parsing. If groups_spec
is always nested (/
), you could use purrr::reduce(syms(groups_spec), call2, .fn = "/")
to create the expression.!!
is required when passing the input, as otherwise it would try to aggregate a column called spec_expr
. You can think of !!
as replacing the name (spec_expr
) with its value (Purpose * (Region / State)
).Big applause, @mitchelloharawild ! I could not figure this out for days.
Appreciate your help on this (especially constructing the expression from scratch, rather than parsing).
Thank you.
No worries, apologies for the delay in responding!
Is there a way how can I use
aggregate_key
in function? I am trying to construct the.spec
argument as an argument to function.I tried to use
str_c
andstr_glue
, with various usage ofunquos
and!!
, but no success.