[R] Help with Moving Average in R

Saji Ren saji.ren at gmail.com
Mon Dec 28 07:54:47 CET 2009


Hello,guys:

I want to use a moving average estimation in my analysis.
When refering to this "moving average", I mean a MA in a technical analysis definition, and not to the definition in Time Series Analysis.
Actually, it is an AR estimation in TSA.

So I use the function "filter" to compute it. For example, i compute the ma2 as below:

> x = 1:10
> ma2 = filter(x,rep(1/2, 2),sides =1)
> ma2
 [1]  NA 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5

Note that the ma2 estimation use the current value as an input, and i want to avoid this.
I mean I just want to use the past values x[t-2] and x[t-1] to get the ma2, and use that as the current estimation.
So that is actually a ma3 with the coefficient c(1/2, 1/2, 0), so i use the command as below:

> MA2 = filter(x,c(rep(1/2,2),0),sides = 1)
> MA2
 [1]  NA  NA 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5

But what I want is:
[1]  NA  NA 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5

And I think the command I used to get MA2 should give a result as what I want, but it just does not.
I want to know the reason, and I wondor if anyone could introduce a more convinient way to compute that.

Thank you all in advance
Saji from Shanghai


More information about the R-help mailing list