I have 2 time series and I am using ccf to find the cross correlation between them.
ccf(ts1, ts2) lists the cross-correlations for all time lags. H
Because 3 is more than 4, I also had a stab at modifying this function, this time by implementing an idea from here:
ccfmax <- function(a, b, e=0)
{
d <- ccf(a, b, plot = FALSE, lag.max = length(a)/2)
cor = d$acf[,,1]
abscor = abs(d$acf[,,1])
lag = d$lag[,,1]
res = data.frame(cor, lag)
absres = data.frame(abscor, lag)
maxcor = max(absres$abscor)
absres_max = res[which(absres$abscor >= maxcor-maxcor*e &
absres$abscor <= maxcor+maxcor*e),]
return(absres_max)
}
Essentially an "error" term is added, so that if there are several values close to the maximum, they all get returned, eg:
ayy <- jitter(cos((1:360)/5), 100)
bee <- jitter(sin((1:360)/5), 100)
ccfmax(ayy, bee, 0.02)
cor lag
348 0.9778319 -8
349 0.9670333 -7
363 -0.9650827 7
364 -0.9763180 8
If no value for e is given it is taken to be zero, and the function behaves just like the one nvogen posted.