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


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

# Create data frame
df <- data.frame(month=1:8,

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


[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.