I have a string a time-series data which I am trying to decompose. Each data-point corresponds to the start date of a given month and looks something like:
A <- c(5,6,7,8,9,8,5,6,10,11)
I convert the data to a time-series using the following:
A1 <- as.ts(A, frequency=12)
Then I try to decompose using:
decompose(A1)
I get the following error:
time series has no or less than 2 periods`
I have also used the zoo
package to create a similar time-series, but get the same result.
Any thoughts?
As can be seen from the source code of decompose()
function your data has to have a frequency above 1 and the number of non-missing data points should be at least 2 times the frequency value:
> decompose
function (x, type = c("additive", "multiplicative"), filter = NULL) {
type <- match.arg(type)
l <- length(x)
f <- frequency(x)
if (f <= 1 || length(na.omit(x)) < 2 * f)
stop("time series has no or less than 2 periods")
...
In your case the error is thrown because the time series (the way it was constructed) has a frequency of 1:
A <- c(5,6,7,8,9,8,5,6,10,11)
A1 <- as.ts(A, frequency=12)
> frequency(A1)
# 1
You can construct a time series object with the correct frequency calling ts
instead of as.ts
:
A1 <- ts(A, frequency=12)
> frequency(A1)
# 12
However in this case the same error will get triggered because you have 10 observations, when the required number is at least 24.
In order to make it work - have at least 24 observations:
A1 <- ts(runif(24, 1, 100), frequency=12)
decompose(A1)
# works.