我有10000多行的动物园对象.
> 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
Run Code Online (Sandbox Code Playgroud)
我尝试了以下行的变体,但无济于事.
rollapply(tt, 21, function(x) cor(x[,1],x[,2]))
Run Code Online (Sandbox Code Playgroud)
每个条目都给出1的相关性,看起来它正在从相关矩阵的对角线上取下1.
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
Run Code Online (Sandbox Code Playgroud)
我真正想要的是-0.4649,如下所示
> cor(tt)
A B
A 1.0000000 -0.4649881
B -0.4649881 1.0000000
Run Code Online (Sandbox Code Playgroud)
Jos*_*ich 12
对于您的简单案例,您可以使用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))
Run Code Online (Sandbox Code Playgroud)
尝试这样的事情:
x<-rnorm(100)
y<-rnorm(100)
rollapply(data.frame(x,y), 21 ,function(x) cor(x[,1],x[,2]), by.column=FALSE)
Run Code Online (Sandbox Code Playgroud)
换句话说,我认为你可能只需要这个by.column=FALSE论点.也适用于动物园对象
rollapply(zoo(cbind(x,y),Sys.Date()-1:100), 21 ,function(x) cor(x[,1],x[,2]), by.column=FALSE)
Run Code Online (Sandbox Code Playgroud)
您可以指定要在cor函数中使用的列.
z<-rnorm(100)
rollapply(zoo(cbind(x,y,z),Sys.Date()-1:100), 21 ,function(x) cor(x[,1],x[,3]), by.column=FALSE)
rollapply(zoo(cbind(x,y,z),Sys.Date()-1:100), 21 ,function(x) cor(x[,2],x[,3]), by.column=FALSE)
Run Code Online (Sandbox Code Playgroud)
by.column=FALSE表示该函数不应单独应用于每个列.如果by.column=TRUE,那么该函数将分别应用于每个列,这是默认行为.
| 归档时间: |
|
| 查看次数: |
14104 次 |
| 最近记录: |