How to Calculate Rolling Correlation in R?
In this article, we will discuss Rolling Correlation in R Programming Language.
Correlation is used to get the relationship between two variables.
- It will result in 1 if the correlation is positive.
- It will result in -1 if the correlation is negative.
- it will result in 0 if there is no correlation.
Rolling correlations are used to get the relationship between two-time series on a rolling window. We can calculate by using rollapply() function, This is available in the zoo package, So we have to load this package.
Syntax:
rollapply(data, width, FUN, by.column=TRUE)
where,
- data is the input dataframe.
- width is an integer that specifies the window width for the rolling correlation.
- FUN is the function to be applied.
- by.column is used to specify whether to apply the function to each column separately.
We can get correlation using cor() function.
Syntax:
cor(column1,column2)
Example 1: R program to calculate rolling correlation for the dataframe.
R
# load the library library (zoo) # create dataframe with 3 columns data = data.frame (day=1:15, col1= c (35:49), col2= c (33:47)) # display print (data) # get rolling correlation for col1 and # col2 with width 6 print ( rollapply (data, width=6, function (x) cor (x[,2],x[,3]), by.column= FALSE )) |
Output:
Example 2:
R
# load the library library (zoo) # create dataframe with 3 columns data = data.frame ( col1= c (23,45,23,32,23), col2= c (1,45,67,32,45)) # display print (data) # get rolling correlation for col1 and # col2 with width 2 print ( rollapply (data, width=2, function (x) cor (x[,1],x[,2]), by.column= FALSE )) |
Output: