1
votes

Say, I have two vectors of the same length

A = mtcars$mpg
B = mtcars$cyl

I can calculate correlation between whole vectors

cor (A, B)

and get one single value (-0.852162).

What I need is to calculate correlation between the two vectors with a sampling rate of 10, which means I start at the first datapoint in A and B, take 5 values on the right from it (there are no values on the left), calculate a correlation coefficient ad write it in a vector C. Then I take the next value in A & B, take 5 values on the right and 1 on the left, write it into a vector; then shift again to the next value and so forth. The resulting vector C must contain the same number of values as A or B (N=32), and each value in C represents a correlation b/w A and B with a sampling rate 10 (5 values on the left and 5 on the right from that datapoint, if availible). Is there any elegant and simple way to do it in R?

P.S.: The ease of coding is more important, than the time needed for calculations.

1

1 Answers

1
votes

The TTR package may provide what you are looking for.

It should be as simple as:

TTR::runCor(A, B)

There is a whole blog post about rolling correlation here.