There is also rollmean in the zoo package which might be slightly faster since its optimized for that operation. k * rollmean(x, k) e.g.
> 2 * rollmean(1:4, 2) [1] 3 5 7 will give a rolling sum. runmean in the caTools package is even faster. On Fri, Apr 2, 2010 at 2:31 PM, Jorge Ivan Velez <jorgeivanve...@gmail.com> wrote: > Hi Andy, > > Take a look at the rollapply function in the zoo package. > >> require(zoo) > Loading required package: zoo >> x <- 1:4 >> rollapply(zoo(x), 1, sum) > 1 2 3 4 > 1 2 3 4 >> rollapply(zoo(x), 2, sum) > 1 2 3 > 3 5 7 >> rollapply(zoo(x), 3, sum) > 2 3 > 6 9 >> rollapply(zoo(x), 4, sum) > 2 > 10 > > # all at once > sapply(1:4, function(r) rollapply(zoo(x), r, sum)) > > > HTH, > Jorge > > > On Fri, Apr 2, 2010 at 2:24 PM, Andy Rominger <> wrote: > >> Hello, >> >> I'd like to take all possible sub-summands of a vector in the quickest and >> most efficient way possible. By "sub-summands" I mean for each sub-vector, >> take its sum. Which is to say: if I had the vector >> >> x<-1:4 >> >> I'd want the "sum" of x[1], x[2], etc. And then the sum of x[1:2], x[2:3], >> etc. And then...so on. >> >> The result would be: >> 1 2 3 4 >> 2 5 7 >> 6 9 >> 10 >> >> I can do this with for loops (code below) but for long vectors (10^6 >> elements) looping takes more time than I'd like. Any suggestions? >> >> Thanks very much in advance-- >> Andy >> >> >> # calculate sums of all sub-vectors... >> x <- 1:4 >> >> sub.vect <- vector("list",4) >> >> for(t in 1:4) { >> maxi <- 4 - t + 1 >> this.sub <- numeric(maxi) >> for(i in 1:maxi) { >> this.sub[i] <- sum(x[i:(i+t-1)]) >> } >> sub.vect[[t]] <- this.sub >> } >> >> sub.vect >> >> [[alternative HTML version deleted]] >> >> ______________________________________________ >> 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. >> > > [[alternative HTML version deleted]] > > ______________________________________________ > 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.