fabletools icon indicating copy to clipboard operation
fabletools copied to clipboard

Add function to create combination model, given a mable

Open raneameya opened this issue 3 years ago • 2 comments

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?

raneameya avatar Jul 23 '21 08:07 raneameya

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')

brunocarlin avatar Jul 23 '21 14:07 brunocarlin

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.

raneameya avatar Jul 28 '21 00:07 raneameya