Hi,
I can extract elements from non-bootstrapped and bootstrapped forecasts in fable using matrix and unlist, but would like a tidyverse version.
For non-bootstrapped forecasts, I want to extract the mean and variance (or sd) of the forecast distribution at EACH time-step, as individuals numbers e.g. mu1, sd1, mu2, sd2, etc.
For bootstrapped forecasts, I want to extract the 5000 bootstrapped samples at EACH time-step and stack them ALL in a tibble.
Here's a reproducible example
library(fpp3)
caf_fit <- global_economy |>
filter(Code == "CAF") |>
model(arima210 = ARIMA(Exports ~ pdq(2,1,0)))
caf_fit |> report()
# Non-Bootstrapped forecasts
# --------------------------
fc <- caf_fit |>
forecast(h = 5, bootstrap = FALSE)
fc |> pull(Exports)
fc[[4]][[1]]
fc[[4]][[2]]
fc[[4]][[3]]
fc[[4]][[4]]
fc[[4]][[5]]
mu1 <- t(matrix(unlist(fc[[4]][1]), ncol = 1))[1]
sd1 <- t(matrix(unlist(fc[[4]][1]), ncol = 1))[2]
mu2 <- t(matrix(unlist(fc[[4]][2]), ncol = 1))[1]
sd2 <- t(matrix(unlist(fc[[4]][2]), ncol = 1))[2]
# etc
# Bootstrapped forecasts
# ----------------------
fc_B <- caf_fit |>
forecast(h = 5, bootstrap = TRUE)
fc_B
str(fc_B)
# make tb_B bootstrap forecasts
fc.B.1 <- rep(0, 5000)
fc.B.2 <- rep(0, 5000)
fc.B.3 <- rep(0, 5000)
fc.B.4 <- rep(0, 5000)
fc.B.5 <- rep(0, 5000)
for (i in 1:5000) {
fc.B.1[i] <- t(matrix(unlist(fc_B[[4]][1]), ncol = 1))[i]
fc.B.2[i] <- t(matrix(unlist(fc_B[[4]][2]), ncol = 1))[i]
fc.B.3[i] <- t(matrix(unlist(fc_B[[4]][3]), ncol = 1))[i]
fc.B.4[i] <- t(matrix(unlist(fc_B[[4]][4]), ncol = 1))[i]
fc.B.5[i] <- t(matrix(unlist(fc_B[[4]][5]), ncol = 1))[i]
}
fc_B_1 <- as_tibble(fc.B.1)
fc_B_2 <- as_tibble(fc.B.2)
fc_B_3 <- as_tibble(fc.B.3)
fc_B_4 <- as_tibble(fc.B.4)
fc_B_5 <- as_tibble(fc.B.5)
tb_B <- bind_rows(
list(
f01_B = fc_B_1,
f02_B = fc_B_2,
f03_B = fc_B_3,
f04_B = fc_B_4,
f05_B = fc_B_5
),
.id = "id"
)
head(tb_B)
Is there a more efficient way?
thanks,
Amarjit