tidyverts / fabletools

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

Add function to create combination model, given a mable #323

Open raneameya opened 3 years ago

raneameya commented 3 years ago

Having a function automatically create a simple average combination model would be very convenient. Here's a simple way it could work -

library(tsibble)
library(fable)

addCombn <- function(m, name) {
  mv <- mable_vars(m)
  m[[name]] <- Reduce(f = '+', as.list(m[, mv])) / length(mv)
  return(m)
}

m <- tourism %>%
  dplyr::filter(Region == 'Adelaide' & Purpose == 'Business') %>%
  model(
    E = ETS(Trips), 
    A = ARIMA(Trips), 
    T = THETA(Trips)
  ) %>%
  addCombn('EAT')

This almost works as desired. See below -

mable_vars(m) # misses 'EAT'
[1] "E" "A" "T"
m$cc <- 1L
m$cc <- NULL
mable_vars(m) # desired outcome
[1] "E" "A" "T" "EAT"

I think there's something subtle that I'm missing, maybe some shallow copies?

brunocarlin commented 3 years ago

I think it was made to be used alongside mutate

library(tsibble)
library(fable)
library(tidyverse)

addCombn <- function(m, name) {
  mv <- mable_vars(m)
  m |> 
    mutate(!!name := Reduce(f = '+', as.list(m[, mv])) / length(mv))
}

m <- tourism %>%
  dplyr::filter(Region == 'Adelaide' & Purpose == 'Business') %>%
  model(
    E = ETS(Trips), 
    A = ARIMA(Trips), 
    T = THETA(Trips)
  ) %>%
  addCombn('EAT')
raneameya commented 3 years ago

That seems a bit restrictive to me. It does work without mutate, provided one uses the $ way of subsetting & assignment. for example, if I would have m$name <- Reduce(f = '+', as.list(m[, mv])) / length(mv), then it would work no problem. But programatically providing the name is where I ran into an issue.