robjhyndman / anomalous-acm

Anomalous time series package for R (ACM)
119 stars 30 forks source link

Error when running with constant time series and normalization #4

Closed cbergmeir closed 7 years ago

cbergmeir commented 7 years ago

Hi,

I noticed that the tsmeasures function will terminate with an error if run on constant time series as follows:

> tsmeasures(cbind(rep(3,50), rep(4,50))) Error in acf(x, plot = FALSE, na.action = na.exclude) : 'lag.max' must be at least 0 In addition: Warning message: In acf(x, plot = FALSE, na.action = na.exclude) : NAs introduced by coercion

The problem is that in the following line in the tsmeasures function:

if (normalise) { x <- as.ts(scale(x, center = TRUE, scale = TRUE)) # Normalise data to mean = 0, sd = 1 }

if the series is constant, scale will divide by 0, so that you get a series consisting of NaN. Then, later on, when acf() is executed on this NaN series, it throws the error.

Solution would be probably to check in the normalization if the series is constant, and if it is, not use the scale.

i.e., instead of: x <- as.ts(scale(x, center = TRUE, scale = TRUE))

you could use something like:

x <- as.ts(scale(x, center = TRUE, scale = !(abs(max(x) - min(x)) < 1e9)))

robjhyndman commented 7 years ago

You can use the is.constant() function from the forecast package. Can you do a PR?

cbergmeir commented 7 years ago

Ok, I created a pull request...as yo don't yet import the forecast package I copied the function, as it is very simple and to not introduce that otherwise unnecessary dependency.