Autocorrelation Functions

One important property of a time series is the autocorrelation function. You can estimate the autocorrelation function for time series using R’s acf function:

acf(x, lag.max = NULL,
    type = c("correlation", "covariance", "partial"),
    plot = TRUE, na.action = na.fail, demean = TRUE, ...)

The function pacf is an alias for acf, except with the default type of "partial":

pacf(x, lag.max, plot, na.action, ...)

By default, this function plots the results. (An example plot is shown in Plotting Time Series.) As an example, let’s show the autocorrelation function of the turkey price data:

> library(nutshell)
> data(turkey.price.ts)
> acf(turkey.price.ts, plot=FALSE)

Autocorrelations of series ‘turkey.price.ts’, by lag

0.0000 0.0833 0.1667 0.2500 0.3333 0.4167 0.5000 0.5833 0.6667 0.7500 
 1.000  0.465 -0.019 -0.165 -0.145 -0.219 -0.215 -0.122 -0.136 -0.200 
0.8333 0.9167 1.0000 1.0833 1.1667 1.2500 1.3333 1.4167 1.5000 1.5833 
-0.016  0.368  0.723  0.403 -0.013 -0.187 -0.141 -0.180 -0.226 -0.130 

> pacf(turkey.price.ts,plot=FALSE)

Partial autocorrelations of series ‘turkey.price.ts’, by lag

0.0833 0.1667 0.2500 0.3333 0.4167 0.5000 0.5833 0.6667 0.7500 0.8333 
 0.465 -0.300 -0.020 -0.060 -0.218 -0.054 -0.061 -0.211 -0.180  0.098 
0.9167 1.0000 1.0833 1.1667 1.2500 1.3333 1.4167 1.5000 1.5833 
 0.299  0.571 -0.122 -0.077 -0.075  0.119  0.064 -0.149 -0.061

The function ccf plots the cross-correlation function for two time series:

ccf(x, y, lag.max = NULL, type = c("correlation", "covariance"),
    plot = TRUE, na.action = na.fail, ...)

By default, this function will plot the results. You can suppress the plot (to just view the function) with the argument plot=FALSE.

As an example of cross-correlations, we can use average ham prices in the United States. These are included in the nutshell package as ham.price.ts:

> library(nutshell)
> data(ham.price.ts)
> ccf(turkey.price.ts, ham.price.ts, plot=FALSE)

Autocorrelations of series 'X', by lag

-1.0833 -1.0000 -0.9167 -0.8333 -0.7500 -0.6667 -0.5833 -0.5000 -0.4167 
  0.147   0.168  -0.188  -0.259  -0.234  -0.098  -0.004   0.010   0.231 
-0.3333 -0.2500 -0.1667 -0.0833  0.0000  0.0833  0.1667  0.2500  0.3333 
  0.228   0.059  -0.038   0.379   0.124  -0.207  -0.315  -0.160  -0.084 
 0.4167  0.5000  0.5833  0.6667  0.7500  0.8333  0.9167  1.0000  1.0833 
 -0.047  -0.005   0.229   0.223  -0.056  -0.099   0.189   0.039  -0.108

You can apply filters to a time series with the filter function or convolutions (using fast Fourier transforms [FFTs]) with the convolve function.