2017-10-11 112 views
0

我試圖在兩個data.table列之間進行滾動關聯。Rolling correlation with data.table

dt <- data.table(a=-1:10,b=1:12) 
> dt 
    a b 
1: -1 1 
2: 0 2 
3: 1 3 
4: 2 4 
5: 3 5 
6: 4 6 
7: 5 7 
8: 6 8 
9: 7 9 
10: 8 10 
11: 9 11 
12: 10 12 

這就是我一直在使用rollapplyzoo嘗試:

library(zoo) 
dt[,rcor:=rollapplyr(as.list(a,b),width=5, 
        FUN=function(y) {return(cor(y[[1]],y[[2]]))},fill=NA)] 

Error in zoo(data) : 「x」 : attempt to define invalid zoo object 

roll_corroll

library(roll) 
roll_cor(dt[,.(a,b)],5) 
Error in roll_cor(dt[, .(a, b)], 5) : 
    Not compatible with requested type: [type=list; target=double]. 

回答

1

試試這個:

corr <- function(y) cor(y[, 1], y[, 2]) 
dt[,rcor:=rollapplyr(.SD, 5, corr, by.column = FALSE, fill = NA)] 
+0

很棒。謝謝。 –