[R] unavoidable loop? a better way??

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Nov 13 09:00:49 CET 2004


Ah, that is now a recursive linear filter.  In fact filter() would do both 
your examples.

On Sat, 13 Nov 2004, James Muller wrote:

> Take 3:
>
> # p is a vector
> myfunc <- function (p) {
>   x <- rep(0,length(p))
>   x[1] <- p[1]
>   for (i in c(2:length(p))) {
>     x[i] <- 0.8*p[i] + 0.2*x[i-1]   # note the x in the last term
>   }
>   return (x)
> }
>
> James
>
>
>
>
>
> On Sat, 13 Nov 2004 01:12:50 -0600, Deepayan Sarkar <deepayan at stat.wisc.edu> 
> wrote:
>
>> On Saturday 13 November 2004 00:51, James Muller wrote:
>>> Hi all, I have the following problem, best expressed by my present
>>> solution:
>>> 
>>> # p is a vector
>>> myfunc <- function (p) {
>>>    x[1] <- p[1]
>>>    for (i in c(2:length(p))) {
>>>      x[i] <- 0.8*p[i] + 0.2*p[i-1]
>>>    }
>>>    return (x)
>>> }
>> 
>> Does this work at all? I get
>> 
>>> myfunc <- function (p) {
>> +    x[1] <- p[1]
>> +    for (i in c(2:length(p))) {
>> +      x[i] <- 0.8*p[i] + 0.2*p[i-1]
>> +    }
>> +    return (x)
>> + }
>>> 
>>> myfunc(1:10)
>> Error in myfunc(1:10) : Object "x" not found
>> 
>> 
>> Anyway, simple loops are almost always avoidable. e.g.,
>> 
>> myfunc <- function (p) {
>>    x <- p
>>    x[-1] <- 0.8 * p[-1] + 0.2 * p[-length(p)]
>>    x
>> }
>> 
>> Deepayan
>> 
>>> 
>>> That is, I'm calculating a time-weighted average. Unfortunately the
>>> scale of the problem is big. length(p) in this case is such that each
>>> call takes about 6 seconds, and I have to call it about 2000 times
>>> (~3 hours). And, I'd like to do this each day. Thus, a more efficient
>>> method is desirable.
>>> 
>>> Of course, this could be done faster by writing it in c, but I want
>>> to avoid doing that if there already exists something internal to do
>>> the operation quickly (because I've never programmed c for use in R).
>>> 
>>> Can anybody offer a solution?
>>> 
>>> I apologise if this is a naive question.
>>> 
>>> James
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list