简体   繁体   中英

Rolling correlation with data.table

I'm trying to do a rolling correlation between two data.table columns.

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

Here's what I've tried using rollapply from zoo :

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

and with roll_cor from roll :

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].

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM