rcorrelation

issue with rolling correlations in R


I want to measure rolling correlations between 2 vectors. If I choose a window width and I measure the correlations, most of the commands will add this correlation not in the center of the window, but at the end.

For example, if the window width is 9, the first correlation coefficient will be in the 9th row. However, the coefficients measured reflects the correlation on average during the window, so that the coefficient should be in the 5th row.

Does anyone know a command (or a package) that would allow me to center the result, because manually it often becomes hard to adjust correctly with the dates.


Solution

  • rollapply defaults to centered alignment. Using the built in BOD data.frame:

    library(zoo)
    
    rollapply(BOD, 3, \(x) cor(x[, 1], x[, 2]), by.column = FALSE, fill = NA)
    ## [1]         NA  0.9404315  0.6449020 -0.9148074  0.9131459         NA
    
    # check
    
    cor(BOD[1:3, 1], BOD[1:3, 2])
    ## [1] 0.9404315
    
    cor(BOD[2:4, 1], BOD[2:4, 2])
    ## [1] 0.644902