title: Exponential moving average of a vector in R
body: <p>I have a simple vector as follows:</p>
  <pre><code>x = c(14.24, 13.82, 12.75, 12.92, 12.94, 13.00, 14.14, 16.28, 20.64, 17.64)
  </code></pre>
  <p>I am trying to find the rolling EMA of this vector using the following function -</p>
  <pre><code>library(TTR)
  y = EMA(x, 5)
  </code></pre>
  <p>I am getting the result as follows -</p>
  <pre><code> [1]     NA     NA     NA     NA 13.33400 13.22267 13.52844 14.44563 16.51042 16.88695
  </code></pre>
  <p>However, I want the result as below -</p>
  <pre><code> [1]     14.24 14.03 13.06 13.43 13.33400 13.22267 13.52844 14.44563 16.51042 16.88695
  </code></pre>
  <ol>
  <li>The first value should be the same as in the original vector</li>
  <li>The second value should be the EMA of the first and second value</li>
  <li>The third value should be the EMA of the initial three values in the
  vector</li>
  <li>The fourth value should be the EMA of the initial four values in the vector</li>
  </ol>
  <p>The rest of the calculation is correctly handled by the function <code>EMA</code></p>
  <p><strong>Solutions I tried -</strong></p>
  <ol>
  <li><p>Running the following command -
  <code>zoo::rollapplyr(x, width = 5, FUN = EMA, partial = TRUE)</code> will give error as EMA has its own rolling window.</p>
  </li>
  <li><p>Using function <code>stats::filter</code> works but the answer is not correct as I am not sure about the right value of the ratio parameter. <a href="https://stackoverflow.com/questions/42774001/fast-r-implementation-of-an-exponentially-weighted-moving-average/42774596#42774596">Fast R implementation of an Exponentially Weighted Moving Average?</a>
  Here is a custom function.</p>
  </li>
  </ol>
  <pre><code>ema_2 &lt;- function (k, width) {
    ratio &lt;- 2/(width + 1)
    c(stats::filter(k * ratio, 1 - ratio, &quot;convolution&quot;, init = k[1]))
  }
  </code></pre>
  <p><strong>The ideal solution should take at most twice the computation time as taken by <code>EMA</code> function of <code>TTR</code> library.</strong></p>
  <p>Here are the performance results of the 2 solutions shared by Waldi and Andre.</p>
  <pre><code>              expr     min       lq     mean   median       uq      max neval cld
      TTR::EMA(x, 5) 433.593 457.5815 500.9478 477.0535 530.7105  1128.49  1000   a
          EMA3(x, 5) 445.388 468.9585 515.2009 490.4345 546.5025  1843.46  1000   a
   rollmeanEMA(x, 5) 436.689 461.0885 535.7035 481.8815 538.3150 33122.75  1000   a
  </code></pre>
  <p>Thanks!</p>