tidyverts / fabletools

General fable features useful for extension packages
http://fabletools.tidyverts.org/
89 stars 31 forks source link

.spec in aggregate_key used in function #307

Closed tomasjanikds closed 3 years ago

tomasjanikds commented 3 years ago

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.

groups_spec <- c('geo', region', subregion')

format_data <- function(raw_data, groups_spec) {

  raw_data %>%
  as_tsibble(.,
             key = groups_spec,
             index = fiscal_period) %>%
  aggregate_key(.,
                groups_spec
                revenue = sum(revenue, na.rm = TRUE))
 }

I tried to use str_c and str_glue, with various usage of unquos and !!, but no success.

groups_spec <- c('geo', region', subregion')

format_data <- function(raw_data, groups_spec) {

  agg_key <- str_c(groups_spec, collapse = '/')

  raw_data %>%
  as_tsibble(.,
             key = groups_spec,
             index = fiscal_period) %>%
  aggregate_key(.,
                agg_key
                revenue = sum(revenue, na.rm = TRUE))
 }
mitchelloharawild commented 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,

tomasjanikds commented 3 years ago

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.

mitchelloharawild commented 3 years ago

No worries, apologies for the delay in responding!