I'd like to pass a rolling window of some columns a custom function, with the actual value of other columns.
Given the example data, and the example function.
Apply myfunc to rolling windows, of size 3, of the variables var1 and var2, and the first values of the param1 and param2.
Example:
For the row 2015-07-03 the myfunc function is passed:
var1=c(1.18,1.27, 1.36)param1=3var2=c(3.55,3.82,4.09)param2=13
The example data
library(dplyr)
myfunc <- function(var1, param1, var2, param2){
c(length(var1), length(var2), param1, param2)
}
d <- data_frame(date = seq(as.Date('2015-07-01'), as.Date('2015-07-12'), by = '1 day'))
d <- d %>%
mutate(var1 = seq(1,2, length=12),
var2 = seq(3,6, length=12),
param1 = rep(seq(1,3, length=3),4),
param2 = rep(seq(11,13, length=3),4))
>d
# A tibble: 12 x 5
date param1 param2 var1 var2
<date> <dbl> <dbl> <dbl> <dbl>
1 2015-07-01 1 11 1 3
2 2015-07-02 2 12 1.09 3.27
3 2015-07-03 3 13 1.18 3.55
4 2015-07-04 1 11 1.27 3.82
5 2015-07-05 2 12 1.36 4.09
6 2015-07-06 3 13 1.45 4.36
7 2015-07-07 1 11 1.55 4.64
8 2015-07-08 2 12 1.64 4.91
9 2015-07-09 3 13 1.73 5.18
10 2015-07-10 1 11 1.82 5.45
11 2015-07-11 2 12 1.91 5.73
12 2015-07-12 3 13 2 6
Desired output:
# A tibble: 12 x 4
date param1 param2 res
<date> <dbl> <dbl> <lst>
1 2015-07-01 1 11 <..>
2 2015-07-02 2 12 <..>
3 2015-07-03 3 13 <..>
4 2015-07-04 1 11 <..>
5 2015-07-05 2 12 <..>
6 2015-07-06 3 13 <..>
7 2015-07-07 1 11 <..>
8 2015-07-08 2 12 <..>
9 2015-07-09 3 13 <..>
10 2015-07-10 1 11 <..>
11 2015-07-11 2 12 <..>
12 2015-07-12 3 13 <..>
where for the row 2015-07-03 the content of d$res is 3,3,3,13
length(var1)andvar2always going to be 3? Is your rolling window size 3 by 1 step?