5

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

1 Answer 1

5

Try this:

corr <- function(y) cor(y[, 1], y[, 2]) dt[,rcor:=rollapplyr(.SD, 5, corr, by.column = FALSE, fill = NA)] 
Sign up to request clarification or add additional context in comments.

1 Comment

Works great. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.