I'm looking to do some correlation work on two times series represented by 2 columns in a datatable. I basically need to be able to run rollapply on one column and be able to access another column in the called function using the current position of rollapply.
Let's consider the following datatable :
> DT = data.table(y=c(1,3,6), v=1:9)
> DT
y v
1: 1 1
2: 3 2
3: 6 3
4: 1 4
5: 3 5
6: 6 6
7: 1 7
8: 3 8
9: 6 9
> ft=function(x) if( mean( x[,2,with=FALSE] ) == 4.5) r=c(r,mean(DT[INDEX:(INDEX+3), mean(v)]) )
> rollapply(DT, width=2, function(x) r=mean(x))
The resulting vector r
would be 2 5
since the condition mean( x[,2,with=FALSE] ) == 4.5)
is true when rollapply gets on rows 2, 5 and 8 (but there aren't 3 rows below the row 8 so you can't get the mean of them).
> r
[1] 2 5
INDEX
is the current row from which rollapply is extracting the vector of length 2 from the datable DT to feed it to the function ft.
I don't know if it's even possible to do that since it might be breaking how the whole apply thing works.