Skip to content
Back to formatted view

Raw Message

Message-ID: <opshd5bwr1z5jgoz@muller>
Date: 2004-11-13T06:51:22Z
From: James Muller
Subject: unavoidable loop? a better way??

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)
}

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