Session Ready
Exercise

Rolling means (in C++)

The vectorized rolling mean function, rollmean3() had good performance but very poor readability. It's really hard to tell that this code calculates a rolling mean, which makes the function harder to debug and to maintain.

The second version, rollmean2(), was slower but easier to read. If we translate this into C++, hopefully, we'll get easy readability and fast performance.

rollmean2() is defined in your workspace; you can print its definition to remind yourself how it works. You will now translate rollmean2() to C++, assigning to rollmean4().

Instructions
100 XP
  • Set res as a NumericVector with length n and values given by the NumericVector's get_na() method.
  • Calculate total as the first window values of x.
  • Calculate the mean at window - 1 as the total divided by the width of the window.
  • In the second loop, update the total by subtracting the i - windowth element of x and adding the ith element of x.