To calculate rolling correlation in R, you can use rollapply() function from zoo package. The Rolling correlation is basically Rolling correlations are correlations between two time series on a rolling window.

The following method shows how you can do it with syntax.

Method: Use rollapply() Function

library(zoo)

rollapply(df, width=3, function(x) cor(x[,2],x[,3]), by.column=FALSE)

The following example shows how to calculate rolling correlation in R.

Use rollapply() to Calculate rolling correlation

Let’s see how we can calculate rolling correlation between column of data frame:

# Load library
library(zoo)

# Create data frame
df <- data.frame(month=1:8,
                 Pressure=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58),
                 Temperature=c(78,89,85,84,81,79,77,85))

# Calculate rolling correlation
rollapply(df, width=3, function(x) cor(x[,2],x[,3]), by.column=FALSE)

Output:

[1] -0.8875682 -0.9028927 -0.8075214  0.5601691  0.9970314  0.2892685

As the output shows rolling correlation between Pressure and Temperature column of data frame with window size 3.