I am performing an autocorrelation process for a vector of time series data. I am looking to create a symmetric matrix composed of autocorrelation for a given time series.
I am using the acf()
function to check my values and it returns:
Autocorrelations of series ‘acfData’, by lag
0 1 2 3 4 5 6 7 8 9 10 11 12 13
1.000 -0.038 0.253 0.266 0.250 0.267 -0.182 0.281 -0.013 -0.067 -0.122 -0.115 -0.023 -0.337
To achieve the matrix I then perform a data.frame change on the data to allow me to slide the values by whatever specified lag:
dataF <- data.frame("data" = acfData)
names(dataF)[1] <- "acfData"
dataLag <- slide(dataF, "acfData", slideBy = -1)
To give:
> head(dataLag)
acfData acfData-1
1 -7 NA
2 5 -7
3 4 5
4 -17 4
5 6 -17
6 -10 6
This gives the correct 2x2 matrix when I just perform a cor()
function:
> cor(na.omit(dataLag))
acfData acfData-1
acfData 1.00000000 -0.03842146
acfData-1 -0.03842146 1.00000000
However expanding this to a second time lag matrix results in the previous values changing.
dataLag <- cbind(dataLag, slide(dataF, "acfData", slideBy = -2)[2])
> head(dataLag)
acfData acfData-1 acfData-2
1 -7 NA NA
2 5 -7 NA
3 4 5 -7
4 -17 4 5
5 6 -17 4
6 -10 6 -17
Performing the cor()
function again results in:
> cor(na.omit(dataLag))
acfData acfData-1 acfData-2
acfData 1.00000000 -0.03156163 0.27502462
acfData-1 -0.03156163 1.00000000 -0.07361449
acfData-2 0.27502462 -0.07361449 1.00000000
As you can see the 1 step lagged data correlation has changed. I assume this is due to the na.omit()
maybe removing the whole first two rows due to the intro of the second lag giving two NA
s, but I am not sure how to omit them correctly for the first lag calculation.
cor(dataLag,use="pairwise.complete.obs")
?ccf
function - see?ccf