How to Calculate Cross Correlation in R?
In this article we will discuss how to calculate cross correlation in R programming language. Correlation is used to get the relation between two or more variables.
- The result is 0, if there is no correlation between two variables
- The result is 1, if there is positive correlation between two variables
- The result is -1, if there is negative correlation between two variables
Cross correlation is used to measure the relationship between a time series and a lagged version of another time series. We can calculate this by using the ccf() method.
Syntax:
ccf(data1,data2)
where, data1 and data2 may be a vector or a dataframe
Return:
It will result the auto correlation lag and plot
Example: Cross correlation between two vectors
R
# create the vector with 10 elements data1= c (1:10) # create the vector with 10 elements data2= c (45:54) # get ccf of the two data print ( ccf (data1,data2)) |
Output:
Example : Auto correlation between two columns in the dataframe
R
# create the dataframe with 2 columns data1= data.frame (a= c (1:10),b= c (23:32)) # get ccf of the two dataframe columns print ( ccf (data1$a,data1$b)) |
Output: