fabletools
fabletools copied to clipboard
Add function to create combination model, given a mable
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?
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')
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.