Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

r - Calculate rolling correlation using rollapply

I have zoo object with 10000+ rows.

> head(tt)
                      A             B
2007-01-04  0.005945924  0.0021167475
2007-01-05 -0.004201991 -0.0080020024
2007-01-08  0.001740897  0.0045804104
2007-01-09  0.000000000 -0.0008163931
2007-01-10 -0.004503531  0.0032615812
2007-01-11 -0.005841138  0.0043863282

I have tried variations of the following line, but to no avail.

rollapply(tt, 21, function(x) cor(x[,1],x[,2]))

Every entry gave correlation of 1, looks like it's picking up the 1 off the diagonal of the correlation matrix.

2013-11-25  1  1
2013-11-26  1  1
2013-11-27  1  1
2013-11-29  1  1
2013-12-02  1  1
2013-12-03  1  1

What I really want is -0.4649, like the following

> cor(tt)
           A          B
A  1.0000000 -0.4649881
B -0.4649881  1.0000000
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For your simple case, you could use TTR::runCor.

set.seed(21)
x <- rnorm(30)
y <- rnorm(30)
z <- zoo(cbind(x,y),Sys.Date()-1:30)
tail(rollapplyr(z, 21, function(x) cor(x[,1],x[,2]), by.column=FALSE))
tail(runCor(z[,1],z[,2],21))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...