Skip to content

Commit

Permalink
Added as_fable.forecast
Browse files Browse the repository at this point in the history
Resolves #239
  • Loading branch information
mitchelloharawild committed Jul 10, 2020
1 parent 4b71ea8 commit 73f05e6
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ S3method(aggregate_key,tbl_ts)
S3method(as_dable,tbl_df)
S3method(as_dable,tbl_ts)
S3method(as_fable,fbl_ts)
S3method(as_fable,forecast)
S3method(as_fable,grouped_df)
S3method(as_fable,grouped_ts)
S3method(as_fable,tbl_df)
Expand Down
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
always match regardless of the value used.
* Using `summarise()` with a fable will now retain the fable class if the
distribution still exists under the same variable name.
* Added `as_fable.forecast()` to convert forecast objects from the forecast
package to work with fable.
* Documentation improvements
* Performance improvements

Expand Down
41 changes: 41 additions & 0 deletions R/fable.R
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,47 @@ as_fable.fbl_ts <- function(x, response, distribution, ...){
#' @export
as_fable.grouped_df <- as_fable.tbl_df

#' @inheritParams forecast.mdl_df
#' @rdname as-fable
#' @export
as_fable.forecast <- function(x, ..., point_forecast = list(.mean = mean)){
if(is.null(x$upper)){
# Without intervals, the best guess is the point forecast
dist <- distributional::dist_degenerate(x$mean)
} else {
if(!is.null(x$lambda)){
x$upper <- box_cox(x$upper, x$lambda)
x$lower <- box_cox(x$lower, x$lambda)
}
warn("Assuming intervals are computed from a normal distribution.")
level <- colnames(x$upper)[1]
level <- as.numeric(gsub("^[^0-9]+|%", "", level))/100
mid <- (x$upper[,1] - x$lower[,1])/2
mu <- x$lower[,1] + mid
sigma <- mid/(qnorm((1+level)/2))
dist <- distributional::dist_normal(mu = as.numeric(mu), sigma = as.numeric(sigma))
if(!is.null(x$lambda)){
dist <- distributional::dist_transformed(
dist,
transform = purrr::partial(inv_box_cox, lambda = x$lambda),
inverse = purrr::partial(box_cox, lambda = x$lambda)
)
}
}
out <- as_tsibble(x$mean)
dimnames(dist) <- "value"
out[["value"]] <- dist

point_fc <- compute_point_forecasts(dist, point_forecast)
out[names(point_fc)] <- point_fc

build_fable(
out,
response = "value",
distribution = "value"
)
}

build_fable <- function (x, response, distribution) {
# If the response (from user input) needs converting
response <- eval_tidy(enquo(response))
Expand Down
8 changes: 8 additions & 0 deletions man/as-fable.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 73f05e6

Please sign in to comment.