Finding lag at which cross correlation is maximum ccf( )

后端 未结 4 2113
野的像风
野的像风 2020-12-23 17:55

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

4条回答
  •  一向
    一向 (楼主)
    2020-12-23 18:47

    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')
    

提交回复
热议问题