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.
 NA NA NA 0.838564 1.528327 3.473569 2.375777
 1.040208 0.224067 -1.936660
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.
 NA NA NA 0.2096409 0.3820817 0.8683924
 0.5939443 0.2600519 0.0560168 -0.4841650
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.
 NA NA NA -0.5604756 -0.2301775 0.0705084
 0.0705084 -1.2650612 -1.2650612 -1.2650612
 NA NA NA 1.558708 1.558708 1.715065 1.715065
 1.715065 1.715065 0.460916
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.