Writing running functions in R can be slow because of the loops
involved. The TTR package contains several run functions
that are very fast because they call Fortran and C routines. With Rcpp and
the C++ STL one can easily write run functions to use in R.

[1] NA NA NA 0.8386 1.5283 3.4736 2.3758 1.0402
[9] 0.2241 -1.9367

Now that we have the function run_sum written, we can easily
use this to write the function run_mean just by dividing
run_sum by n. Another point to note is the syntax
to cast n to a double so we do not lose the decimal points
with integer division.

[1] NA NA NA 0.20964 0.38208 0.86839 0.59394
[8] 0.26005 0.05602 -0.48416

With min_element and max_element from the algorithm header, one can
also easily write a function that calculates the min and the
max of a range over a running window. Note the * to dereference
the iterator to obtain the value. See Finding the minimum of a vector
for another example of using min_element.

[1] NA NA NA -0.56048 -0.23018 0.07051 0.07051
[8] -1.26506 -1.26506 -1.26506

[1] NA NA NA 1.5587 1.5587 1.7151 1.7151 1.7151 1.7151 0.4609

This post demonstrates how to incorporate a few useful functions
from the STL, accumulate, min_element, and
max_element, to write ‘run’ functions with Rcpp.