R/persistence.R

Defines functions persistence

Documented in persistence

#library(devtools)
#document()
#load_all(as.package("../../onlineforecast"))
#?persistence

#' Generate persistence and periodic persistence forecasts
#'
#' Generate a forecast matrix using persistence. The simple persistence is with the current value of y, i.e. the value at time t is used as forecast
#'
#' A seasonal persistence with a specific period can be generated by setting the argument \code{perlen} to the length of the period in steps. The value used for the forecast is then the latest available, which is matches the seasonality for time t+k, see the examples.
#'
#' 
#' @title Generate persistence forecasts
#' @param y (numeric) The model output to be forecasted.
#' @param kseq (integer) The horizons to be forecasted.
#' @param perlen (integer) The period length for seasonal persistence.
#' @return Forecast matrix as a \code{data.frame} (named \code{Yhat} in similar functions)
#' @examples
#'
#' # Simple persistence just copies the current value for the forecasts
#' persistence(1:10, kseq=1:4)
#'
#' # Seasonal persistence takes the value perlen steps back
#' persistence(1:10, kseq=1:4, perlen=4)
#'
#' # If the horizons are longer than perlen, then the perlen*i steps back is taken (i is an integer)
#' persistence(1:10, kseq=1:12, perlen=4)
#'
#' 
#' @export

persistence <- function(y, kseq, perlen=NA){
    if(is.na(perlen)){
        # No periodic, so just regular persistance
        Yhat <- as.data.frame(sapply(kseq, function(k){
            y
        }))
    }else{
        # A periodic persistence
        Yhat <- as.data.frame(sapply(kseq, function(k){
            lagdf(y, (perlen-k)%%perlen)
        }))
    }
    names(Yhat) <- pst("k",kseq)
    return(Yhat)
}

Try the onlineforecast package in your browser

Any scripts or data that you put into this service are public.

onlineforecast documentation built on Oct. 12, 2023, 5:15 p.m.