[R] avoiding loops?

Christian Schulz ozric at web.de
Sun Sep 26 11:14:45 CEST 2004


Hi,

is it possible doing this "moving average" 
without a loop, because it is not really
fast for dim(x) 300.000 50. 
I make some attempts with apply and sapply,but didn't get success  until now.

many thanks , christian


ma <- function(x, FUN=mean, lag=5) 
 { 
         FUN=match.fun(FUN)
         n <-  ncol(x) - lag 
         frame <-  matrix(0,nrow=nrow(x),ncol=n)
         for(k in 1:nrow(frame)){
         for (i in 1:ncol(frame)) { 
         frame[k,i] <- FUN(x[k,i]:x[k,i + lag])
         } }
         return(as.data.frame(frame) )
 }




More information about the R-help mailing list