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
I've modified the original solution as well, in order to loop over the function and output the values corresponding to a character vector of indices (x):
abs.max.ccf <- function(x,a,b) {
d <- ccf(a, b, plot=FALSE, lag.max=length(a)-5)
cor <- d$acf[,,1]
abscor <- abs(d$acf[,,1])
lag <- d$lag[,,1]
abs.cor.max <- abscor[which.max(abscor)]
abs.cor.max.lag <- lag[which.max(abscor)]
return(c(x, abs.cor.max, abs.cor.max.lag))
}
I removed the data.frame part within the function, as it is unnecessarily slow. To loop over each column in a data.frame and return the results to a new data.frame, I use this method:
max.ccf <- lapply(colnames(df), function(x) unlist(abs.max.ccf(x, df$y, df[x])))
max.ccf <- data.frame(do.call(rbind, max.ccf))
colnames(max.ccf) <- c('Index','Cor','Lag')