[R] running sum of a vector

Alexy Khrabrov deliverable at gmail.com
Wed Nov 7 23:59:21 CET 2007


I need a vector with sums of vectors up to each position in the  
original.  The imperative version is simple:

# running sum: the traditional imperative way
sumr.1 <- function(x) {
   s <- c()
   ss <- 0
   for (i in 1:length(x)) {
      ss <- ss + x[i]
      s[i] <- ss
   }
   s
}

Yet I want a functional way, which is shorter:

# running sum: functional way, but inefficient one!
sumr.2 <- function(x) {
	sapply(1:length(x), function(i) sum(x[1:i]))
}

-- the problem with the latter is, we need to create indices to run  
over them, and the sum is recomputed anew for each position, while  
the imperative version iterates without recomputing.  Is there a  
better functional solution?

Cheers,
Alexy



More information about the R-help mailing list