tidyverts / tsibble

Tidy Temporal Data Frames and Tools
https://tsibble.tidyverts.org
GNU General Public License v3.0
530 stars 49 forks source link

FR : a clean generic aggregation method #268

Open arnaud-feldmann opened 2 years ago

arnaud-feldmann commented 2 years ago

Hi, despite the adding of .start and .end for fill_gaps, there is still no clean way to aggregate.

I'd like something like that to work on compatible tsibbles :

agreg_tsibble <- function(x,f=sum,unit) {

  f <- match.fun(f)
  ind <- index(x)
  key <- key(x)

  dates_lims <- pull(x,as.character(ind)) %>%
  {c(min(.,na.rm = TRUE),max(.,na.rm=TRUE))} %>%
  as_date %>%
  {c(floor_date(.[1L],unit),ceiling_date(.[2L],unit,change_on_boundary = TRUE))}

  x %>% 
  fill_gaps(.start = dates_lims[1L],
            .end = dates_lims[2L]) %>% 
  index_by(quarter = ~ yearquarter(.)) %>%
  group_by_key() %>%
  summarize(across(! (!!ind),f))

}

There is some things that forbids that :

It would be a very great feature to add, because right now it's way more complicated to aggregate than in stats::ts.