How can I pass the width
argument of the zoo:rollapply
function to the FUN
function called within rollapply
?
I put the values and widths as columns of a same data.frame
:
library(zoo)
a = data.frame(v = 1:10, w = c(2,1,3,5,2,7,3,2,1,3))
# v w
# 1 1 2
# 2 2 1
# 3 3 3
# 4 4 5
# 5 5 2
# 6 6 7
# 7 7 3
# 8 8 2
# 9 9 1
# 10 10 3
I can do:
rollapply(a$v, a$w, function(x) sum(x), partial=T)
Which gives:
[1] 3 2 9 20 11 42 21 17 9 19
Now I would like to use, for each rolling window of a$v
, the corresponding value of a$w
in the computation. For example:
rollapply(a$v, a$w, function(x) sum(x) + a$w[1], partial=T)
But instead of having a$w[1]
as a constant value (here, it simply adds 2 to the values above), I would like to use the value in a$w
corresponding each time to the a$w
(i.e., in the same row of a
).
Hence the desired output would be:
[1] 5 3 12 25 13 49 24 19 10 22