[R] General "moving" functions
Martyn Plummer
plummer at iarc.fr
Thu May 2 14:52:17 CEST 2002
Something like this perhaps?
foo <- function(x, FUN, lag)
{
FUN=match.fun(FUN)
n <- length(x) - lag
y <- numeric(n)
for (i in 1:n) {
y[i] <- FUN(x[i:(i + lag)])
}
return(y)
}
On 02-May-2002 Neil Osborne wrote:
> Thanks,
>
> But not quite what I'm after. What I need is a way to perform a function on
> contiguous subsets of a time series.
>
> For example:
>
> if x is a vector (length > 9), then :
>
> day<-5
> mean(x[day:(day+4)])
>
> will give me a scalar: the mean of the data points passed to the mean
> function.
>
> What I want to do is:
>
> 1) return a vector of the moving means
> 2) be able to use any function I want (as opposed to just mean
>
>
> I would also like the function to be generic ala "outer" which takes a
> function name (pointer?) as one of its arguments.
>
> Any help will be much appreciated.
>
>>From: Prof Brian D Ripley <ripley at stats.ox.ac.uk>
>>To: Neil Osborne <r_stuff_online at hotmail.com>
>>CC: r-help at stat.math.ethz.ch
>>Subject: Re: [R] General "moving" functions
>>Date: Thu, 2 May 2002 10:43:38 +0100 (BST)
>>
>>filter() in package ts.
>>
>>On Thu, 2 May 2002, Neil Osborne wrote:
>>
>> > General "moving" function.
>> >
>> > I'm a relatively new comer to R, and I've only just started writing my
>>own R
>> > functions. However, I need some help for something which I'm sure is
>>quite
>> > straight forward.
>> >
>> > I want to write a function that will allow me to calculate "moving
>>results"
>> > for a given vector. Ideally, the function will be of the form
>> >
>> >
>> > foo<-function(vector1, funcname, lag)
>> > {
>> >
>> > }
>> >
>> > for example, if I use arguments :
>> >
>> > funcname = mean
>> > lag = 10
>> >
>> >
>> > Then foo will return a vector of 10 day moving average
>> >
>> > Many Thanks
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list