title: Adaptive moving average - top performance in R
body: <p>I am looking for some performance gains in terms of rolling/sliding window functions in R. It is quite common task which can be used in any ordered observations data set. I would like to share some of my findings, maybe somebody would be able to provide feedback to make it even faster.<br>
  Important note is that I focus on the case <code>align="right"</code> and adaptive rolling window, so <code>width</code> is a vector (same length as our observation vector). In case if we have <code>width</code> as scalar there are already very well developed functions in <code>zoo</code> and <code>TTR</code> packages which would be very hard to beat (<strong>4 years later</strong>: it was easier than I expected) as some of them are even using Fortran (but still user-defined FUNs can be faster using mentioned below <code>wapply</code>).<br>
  <code>RcppRoll</code> package is worth to mention due to its great performance, but so far there is no function which answers to that question. Would be great if someone could extend it to answer the question.  </p>
  
  <p>Consider we have a following data:</p>
  
  <pre class="lang-r prettyprint-override"><code>x = c(120,105,118,140,142,141,135,152,154,138,125,132,131,120)
  plot(x, type="l")
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/EjUFj.png" alt="plot of chunk make_x"></p>
  
  <p>And we want to apply rolling function over <code>x</code> vector with variable rolling window <code>width</code>.  </p>
  
  <pre class="lang-r prettyprint-override"><code>set.seed(1)
  width = sample(2:4,length(x),TRUE)
  </code></pre>
  
  <p>In this particular case we would have rolling function adaptive to <code>sample</code> of <code>c(2,3,4)</code>.<br>
  We will apply <code>mean</code> function, expected results:</p>
  
  <pre class="lang-r prettyprint-override"><code>r = f(x, width, FUN = mean)
  print(r)
  ##  [1]       NA       NA 114.3333 120.7500 141.0000 135.2500 139.5000
  ##  [8] 142.6667 147.0000 146.0000 131.5000 128.5000 131.5000 127.6667
  plot(x, type="l")
  lines(r, col="red")
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/dWkSZ.png" alt="plot of chunk make_results"></p>
  
  <p>Any indicator can be employed to produce <code>width</code> argument as different variants of adaptive moving averages, or any other function.  </p>
  
  <p>Looking for a top performance.</p>