I would like to create a sliding window where the start of the window is anchored and the end of the window grows in increments of one unit. So in the data frame below the start of the window would stay at 0.10 and the other end would move over 0.08, 0.15 and so on implementing a function each time it moves over column Speed
. If the criteria of the function is not met then the end of the window keeps moving. Once the criteria is met I would like some output in a second column Out
to coincide with all the elements previous in that whole window.
Once the criteria are met then the window terminates before anchoring again at the end of the last window and starting again, growing one unit at a time.
For example, with this data frame the criteria could be that the mean of the window is greater than 0.1 before starting again so:
mean(c(0.10, 0.08)) = 0.09 - criteria not met
mean(c(0.10, 0.08, 0.15)) = 0.11 - criteria met so all previous elements are labelled 'A'
Next:
mean(c(0.13, 0.14)) = 0.14 - criteria met so all previous elements are labelled 'B'
Next:
mean(c(0.08, 0.10)) = 0.09 - criteria not met
mean(c(0.08, 0.10, 0.07)) = 0.08 - criteria not met
mean(c(0.08, 0.10, 0.07, 0.15)) = 0.1 - criteria met so all previous elements are labelled 'C'
Speed Out
0.10 A
0.08 A
0.15 A
0.13 B
0.14 B
0.08 C
0.10 C
0.07 C
0.15 C
I have already tried modifying the solutions in THIS Cross Validated post (answer by @mbq and also by @r_evolutionist without luck. Also I have tied using rollapply
in the package zoo
but I feel this requires a homemade function.