Or try the filter() function (with convolutional filter rep(1/3,3)). Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com
> -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On > Behalf > Of cbe...@tajo.ucsd.edu > Sent: Tuesday, November 27, 2012 4:53 PM > To: r-h...@stat.math.ethz.ch > Subject: Re: [R] code optimisation problem > > Rui Barradas <ruipbarra...@sapo.pt> writes: > > > Hello, > > > > Package 'compiler' is good at optimizing for loops. Try the following. > > > > Or vectorize the function > > > system.time(f1(x,10)) > user system elapsed > 5.01 0.00 5.00 > > system.time(f1.c(x,10)) > user system elapsed > 1.92 0.00 1.91 > > f2 <- function(v,k) diff(cumsum(c(0,v)),lag=k)/k > > system.time(f2(x,10)) > user system elapsed > 0.11 0.00 0.11 > > > Chuck > > > > > #install.packages('compiler') > > library(compiler) > > f1.c <- cmpfun(f1) > > > > N <- 1e6 > > x <- rnorm(N) > > system.time(f1(x, 10)) > > user system elapsed > > 6.77 0.06 6.83 > > system.time(f1.c(x, 10)) > > user system elapsed > > 2.57 0.00 2.57 > > > > > > Hope this helps, > > > > Rui Barradas > > > > Em 27-11-2012 21:43, 47 escreveu: > >> I'd like to write a function that has a vector and a (pos.) number as > >> inputs > >> and returns what is on the picture below (arithmetic means of (k) > >> consecutive elements of a given vector). The problem is it works too slow > >> for long vectors and i know it can be done without "for" loop. However, > >> i've > >> got no idea how. Can anyone help me with that? > >> > >> f1 <- function(v,k) { > >> n <- length(v) > >> z <- (n-k+1) > >> for (i in k:n) { > >> v[i-k+1] <- sum(v[(i-k+1):i]) > >> } > >> v <- v[1:(n-k+1)] > >> v <- v/k > >> return (v) > >> } > [...] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.