Kaja
Kaja

Reputation: 3057

calculating the autocorrelation of a time series in R

As I understand, autocorrelation is a correlation of a set of number with itself.

I know, that I can use acf function to calculate autocorrelation in R, but I want to implement it my self.

I have a time series X[t] and I want to calculate correlation of this time series with X[t-1]

I have done this in R:

ts <- c(1,2,8,1,2,2,3,2,3,2,2,1,3,2,3,1,1,2)
cor(ts,ts-1)

but the correlation is always 1, I think it is not the correct answer. How can I do this in R?

Upvotes: 1

Views: 6149

Answers (2)

ndr
ndr

Reputation: 1437

You want to compute correlation of a time series with a lagged version of itself. First set a lag , and shift the series

require(zoo)
ts <- as.zoo(c(1,2,8,1,2,2,3,2,3,2,2,1,3,2,3,1,1,2))
n <- 3
ts_n <- lag(ts, k=-n, na.pad=T)

then compute correlation while omiting NAs

cor(ts[!is.na(ts_n)], ts_n[!is.na(ts_n)])

Upvotes: 4

Raffael
Raffael

Reputation: 20045

of course the correlation is one in this case because:

> v <- 1:4
> v
 [1]  1  2  3  4
> v-1
 [1] 0 1 2 3

you could corrleate this f.x.:

> v <- runif(5)
> v
[1] 0.8321065 0.1707357 0.7341771 0.2247614 0.1879239

# leaves out first element
> v[-1]
[1] 0.1707357 0.7341771 0.2247614 0.1879239

#leaves out last element
> v[-length(v)]
[1] 0.8321065 0.1707357 0.7341771 0.2247614

> cor(v[-1],v[-length(v)])
[1] -0.6191359

Upvotes: 1

Related Questions