[R] Moving Average Non Uniform Vectors

Luca Cerone luca.cerone at gmail.com
Fri Mar 28 09:48:42 CET 2014


Thanks Jim,
this partially helps (I wasn't aware of the functions you used, which
are good to know).
I have two main doubts about your solution though.
First of all, in my application x is large ~250000 elements and I have
to repeat this for ~1000 different y vectors; moreover the range of x
is much larger than the data I have
(that is, the gaps constitute the majority of the interval), but the
xs are "locally" dense.

Also I am not sure whether the linear interpolation let me have the
results I expect. In your solution, the smoothed data seem to pass
through all my original points,
that is not what I would expect from a smoothing procedure that
removes some noise from the data...

Do you have any other suggestion?
Again thanks for your help;
Luca
Luca Cerone

Tel: +34 692 06 71 28
Skype: luca.cerone


On Thu, Mar 27, 2014 at 8:17 PM, jim holtman <jholtman at gmail.com> wrote:
> Here is one way.  I took your data and applied the 'approx' function to get
> evenly spaced values and then 'filter' to create a moving average of a
> window of size 5.
>
>
> set.seed(1)
> x = c(0,1, 3,3.4, 5, 10, 11.23)
> y = x**2 + rnorm(length(x))
> rbind(x, y)
>
> # create 'even' spacing using the 'approx' function
> steps <- seq(min(x), max(x), length = 100)
> newData <- approx(x, y, xout = steps)
>
> # use filter for running average
>
> avg <- filter(newData$y, rep(1/5, 5))
>
> #plot the data
> plot(x, y, type = 'o')
>
> lines(newData$x, avg, col = 'red')
>
>
>
> Jim Holtman
> Data Munger Guru
>
> What is the problem that you are trying to solve?
> Tell me what you want to do, not how you want to do it.
>
>
> On Thu, Mar 27, 2014 at 12:35 PM, Luca Cerone <luca.cerone at gmail.com> wrote:
>>
>> Dear all,
>> I have a vector x and a vector y = f(x).
>> e.g.
>>
>> x = c(0,1, 3,3.4, 5, 10, 11.23)
>> y = x**2 + rnorm(length(x))
>>
>> I would like to apply a moving average to y, knowing that the x values
>> are not uniformly spaced. How can I do this in R?
>> What alternatives I have to filter out the noise from Y??
>>
>> Thanks in advance for the help!
>>
>>
>>
>>
>> Luca Cerone
>>
>> Tel: +34 692 06 71 28
>> Skype: luca.cerone
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
>




More information about the R-help mailing list