Using TTR package to calculate Exponential moving average
To get the answer you are looking for you would need to write
TTR::EMA(1:20, n=1, ratio=2/(5+1))
[1] 1.000000 1.333333 1.888889 2.592593 3.395062 4.263374 5.175583
[8] 6.117055 7.078037 8.052025 9.034683 10.023122 11.015415 12.010276
[15] 13.006851 14.004567 15.003045 16.002030 17.001353 18.000902
If you call TTR::EMA(1:20, n=5)
it is equivalent to calling
TTR::EMA(1:20, n=5, ratio=2/(5+1))
This will put NA's in the first 4 places and then the 5th place will be the simple mean of the first 5 entries. (i.e. 3 in this case). Then the EMA algorithm will start. The 6th place will be 6 * 2 / 6 + 3 * 4 / 6 = 4. The 7th place will be 7 * 2 / 6 + 4 * 4 / 6 = 5. Etc...
You can see the exact algorithm here
TTR::EMA
calculates the first non-missing value as the arithmetic mean of the first n
variables, then begins calculating recursively. You can match your calculation by setting n=1
and ratio=1/3
.
R> EMA(x,n=1,ratio=1/3)
[1] 1.000000 1.333333 1.888889 2.592593 3.395062 4.263374 5.175583
[8] 6.117055 7.078037 8.052025 9.034683 10.023122 11.015415 12.010276
[15] 13.006851 14.004567 15.003045 16.002030 17.001353 18.000902