PacktPublishing / Hands-On-Time-Series-Analysis-with-R

Hands-On-Time-Series-Analysis-with-R
MIT License
104 stars 88 forks source link

[Page130] lags function error #2

Open RamiKrispin opened 2 years ago

RamiKrispin commented 2 years ago

Fixing error (miscalculation) of the lags on page 130:

The start = start(ts.obj) + l argument add the number of lags to the cycle units of the start argument. For example:

> start(ts.obj) 
[1] 1976    1
> start(ts.obj) + l
[1] 1979    4

Solution - replacing start = start(ts.obj) + l with time(ts_merged)[l + 1]:

# The lags function return the series with its l lags
lags <- function(ts.obj, l){
  ts_merged <- NULL
  # Creating n lags
  for(i in 1:l){
    ts_merged <- ts.union(ts_merged, stats::lag(ts.obj, k = -i))
  }
  # Merge the lags with the original series
  ts_merged <- ts.union(ts.obj, ts_merged)
  # Set the columns names
  colnames(ts_merged) <- c("y", paste0("y_", 1:i))
  # Removing missing values as results of creating the lags
  ts_merged <- window(ts_merged,
                      start = time(ts_merged)[l + 1],
                      end = end(ts.obj))
  return(ts_merged)
}

Thanks for Anoushiravan Razmavar for pointing out this issue!