[R] running sum of a vector

Benilton Carvalho bcarvalh at jhsph.edu
Thu Nov 8 00:08:56 CET 2007


x <- 1:10
cumsum(x)

b

On Nov 7, 2007, at 5:59 PM, Alexy Khrabrov wrote:

> 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
>
> ______________________________________________
> R-help at 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.



More information about the R-help mailing list