I am trying to get the samples from a forecast model generated with fable
. This is what I tried
library(fable)
library(tsibble)
library(tsibbledata)
library(dplyr)
library(tidyr)
# Forecasting with an ETS(M,Ad,A) model to Australian beer production
beer_fc <- aus_production %>%
model(ets = ETS(log(Beer) ~ error("M") + trend("Ad") + season("A"))) %>%
forecast(h = "3 years", bootstrap=TRUE, times = 5)
beer_fc %>% unnest(c(Beer))
The error I get is:
Error: Input must be list of vectors
Here is the structure of the data str(beer_fc$Beer[1])
:
> str(beer_fc$Beer[1])
dist [1:1]
$ :List of 3
..$ dist :List of 1
.. ..$ x: num [1:5] 6.09 6.02 6.06 6 5.95
.. ..- attr(*, "class")= chr [1:2] "dist_sample" "dist_default"
..$ transform:function (.x)
.. ..- attr(*, "class")= chr "transformation"
.. ..- attr(*, "inverse")=function (.x)
..$ inverse :function (.x)
..- attr(*, "class")= chr [1:2] "dist_transformed" "dist_default"
@ vars: chr "Beer"
If we want to extract the 'dist' values into 'long' format, loop over the list
column 'Beer', extract the values, assign it back to the 'Beer' and then unnest
library(purrr)
library(tidyr)
library(dplyr)
beer_fc$Beer <- map(beer_fc$Beer, ~ .x[[1]]$x)
beer_fc %>%
unnest(c(Beer))
-output
# A tibble: 60 x 4
# .model Quarter Beer .mean
# <chr> <qtr> <dbl> <dbl>
# 1 ets 2010 Q3 6.02 402.
# 2 ets 2010 Q3 5.99 402.
# 3 ets 2010 Q3 6.05 402.
# 4 ets 2010 Q3 5.92 402.
# 5 ets 2010 Q3 5.99 402.
# 6 ets 2010 Q4 6.15 470.
# 7 ets 2010 Q4 6.15 470.
# 8 ets 2010 Q4 6.17 470.
# 9 ets 2010 Q4 6.17 470.
#10 ets 2010 Q4 6.12 470.
# … with 50 more rows