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) ) }
Christian Schulz wrote:> Hi, > > is it possible doing this "moving average" > without a loop, because it is not really > fast for dim(x) 300.000 50.On the other hand, building a matrix before consumes too much memory. The best way of doing it is using an already existing function (you might want to look whether, e.g., filter() helps) or porting the loops to C. Uwe Ligges> 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) ) > } > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! R-project.org/posting-guide.html