Last active
June 16, 2023 17:58
-
-
Save dankkom/017fb9af03274814a1d85663df205bfe to your computer and use it in GitHub Desktop.
Functions to extract a data.frame from some forecast objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ts_to_df <- function(ts_data) { | |
dates <- xts:::as.Date.POSIXct(zoo::yearmon(time(ts_data))) | |
values <- zoo::coredata(ts_data) |> | |
tibble::as_tibble() | |
tibble::tibble(date = dates) |> | |
dplyr::bind_cols(values) | |
} | |
HoltWinters_to_df <- function(fcst) { | |
xs <- ts_to_df(fcst$model$x) |> | |
dplyr::rename(original = value) | |
ys <- ts_to_df(fcst$mean) |> | |
dplyr::rename(forecasted = value) | |
lo_df <- fcst$lower |> | |
ts_to_df() |> | |
dplyr::rename_with(~ paste("Lo", .x), .cols = dplyr::where(is.numeric)) | |
up_df <- fcst$upper |> | |
ts_to_df() |> | |
dplyr::rename_with(~ paste("Up", .x), .cols = dplyr::where(is.numeric)) | |
dplyr::bind_rows(xs, ys) |> | |
dplyr::left_join(lo_df, by = c("date")) |> | |
dplyr::left_join(up_df, by = c("date")) | |
} | |
StructTS_to_df <- function(fcst) { | |
xs <- ts_to_df(fcst$model$data) |> | |
dplyr::rename(original = value) | |
ys <- ts_to_df(fcst$mean) |> | |
dplyr::rename(forecasted = value) | |
lo_df <- fcst$lower |> | |
ts_to_df() |> | |
dplyr::rename_with(~ paste("Lo", .x), .cols = dplyr::where(is.numeric)) | |
up_df <- fcst$upper |> | |
ts_to_df() |> | |
dplyr::rename_with(~ paste("Up", .x), .cols = dplyr::where(is.numeric)) | |
dplyr::bind_rows(xs, ys) |> | |
dplyr::left_join(lo_df, by = c("date")) |> | |
dplyr::left_join(up_df, by = c("date")) | |
} | |
auto.arima_to_df <- function(fcst) { | |
xs <- ts_to_df(fcst$model$x) |> | |
dplyr::rename(original = value) | |
ys <- ts_to_df(fcst$mean) |> | |
dplyr::rename(forecasted = value) | |
lo_df <- fcst$lower |> | |
ts_to_df() |> | |
dplyr::rename_with(~ paste("Lo", .x), .cols = dplyr::where(is.numeric)) | |
up_df <- fcst$upper |> | |
ts_to_df() |> | |
dplyr::rename_with(~ paste("Up", .x), .cols = dplyr::where(is.numeric)) | |
dplyr::bind_rows(xs, ys) |> | |
dplyr::left_join(lo_df, by = c("date")) |> | |
dplyr::left_join(up_df, by = c("date")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment