Skip to content
Snippets Groups Projects
make_tday.R 1.59 KiB
Newer Older
  • Learn to ignore specific revisions
  • pbac's avatar
    pbac committed
    ## Do this in a separate tmp.R file to check the documentation
    #library(devtools)
    #document()
    #load_all(as.package("../../onlineforecast"))
    #?make_tday
    
    
    pbac's avatar
    pbac committed
    #' Make an hour-of-day forecast matrix
    
    pbac's avatar
    pbac committed
    #'
    #' This function creates a data.frame with k-steps-ahead values of hour of day,
    #' such that it can be added to a data.list and used inputs to a forecast model.
    #' 
    #' @param time vector of times of class "POSIXct" "POSIXt".
    
    pbac's avatar
    pbac committed
    #' @param kseq vector of integers, representing the desired "k-steps ahead".
    
    pbac's avatar
    pbac committed
    #' @param tstep step time of k in seconds.
    
    pbac's avatar
    pbac committed
    #' @return Returns a forecast matrix (data.frame) with rownames = times, colnames = k1, k2, k3, ...
    #' The content of the data frame is the hour of day.
    
    pbac's avatar
    pbac committed
    #' @keywords hourofday lags data.frame
    
    pbac's avatar
    pbac committed
    #' @seealso make_periodic
    
    pbac's avatar
    pbac committed
    #' @examples
    
    pbac's avatar
    pbac committed
    #' # Create a time sequence of 30 min sample period
    
    #' tseq <- seq(ct("2019-01-01"), ct("2019-02-01 12:00"), by=1800)
    
    pbac's avatar
    pbac committed
    #' 
    
    pbac's avatar
    pbac committed
    #' # Make the time of day sequence (assuming time between k steps is same as for tseq)
    
    pbac's avatar
    pbac committed
    #' make_tday(tseq, 1:10)
    #' 
    
    pbac's avatar
    pbac committed
    #' # With 0.5 hour steps, kstep in hours
    #' make_tday(tseq, 1:10, tstep=3600)
    
    pbac's avatar
    pbac committed
    #'
    #' 
    #' @export
    
    
    pbac's avatar
    pbac committed
    make_tday <- function(time, kseq, tstep=NA){
        # If tstep not given, then take it from time assuming same k-step is the sampling period
        if(is.na(tstep)){
            tstep <- as.numeric(time[2] - time[1], units="secs")
        }
        # The time of day (in the specified units)
    
    pbac's avatar
    pbac committed
        tday <- sapply(kseq, function(k){
            tk <- time + k * tstep
    
    pbac's avatar
    pbac committed
            as.numeric( tk - trunc(tk, units="days"), units="hours")
    
    pbac's avatar
    pbac committed
        })
    
    pbac's avatar
    pbac committed
        # set row and column names
    
    pbac's avatar
    pbac committed
        nams(tday) <- paste0('k', kseq)
        return( as.data.frame(tday) )
    }