robjhyndman / forecast

Forecasting Functions for Time Series and Linear Models
http://pkg.robjhyndman.com/forecast
1.1k stars 340 forks source link

Discrepancy in time units created between ts and forecast #909

Closed bking124 closed 1 year ago

bking124 commented 2 years ago

This is probably a very niche bug, and I'm not sure whether the error is with the ts package or the forecast package. However, I was able to isolate a simple working example. For a bit of background on how I arrived at this error: I was adapting code which forecasted a seasonally adjusted time series, then post-hoc added back in a forecast of the seasonal part. It was in this "adding back" process where the bug was created. Essentially, I tried to create a ts object using the start of the mean coming from a forecast object. Then I wanted to add this ts object to the forecast object mean, but I get a warning:

Warning in .cbind.ts(list(e1, e2), c(deparse(substitute(e1))[1L], deparse(substitute(e2))[1L]), : non-intersecting series

and the result is integer(0). A simple working example that creates this warning is below.

a <- ts(data = rnorm(10), start=c(2017, 14), frequency = 24)
a_fc <- forecast(ets(a), h=1)
b <- ts(1, start=start(a_fc$mean), frequency = 24)
a_fc$mean + b

The mismatch seems to come from a floating point or other numeric type error, as can be seen by running these lines

sprintf("%.30f",tsp(a_fc$mean)[1])
sprintf("%.30f",tsp(b)[1])

which give output of

[1] "2017.958333333333484915783628821373"
[1] "2017.958333333333257542108185589314"

I'm sure I can fairly easily work around this now that I've isolated the error (probably using as.numeric, adding, and then making it a ts again), but still I thought it was worth raising a flag. Let me know if there's any detail I can add.

robjhyndman commented 2 years ago

This sort of thing is super-annoying and arises because ts objects store tsp attributes in floating point rather than integers. The simplest solution is to make b a plain vector:

b <- 1
a_fc$mean + b
bking124 commented 2 years ago

Yes super-annoying is the right description! Took me a long time to realize what was happening. But appreciate the quick reply and thanks for the solution!