# [R] running sum of a vector

Chuck Cleland ccleland at optonline.net
Thu Nov 8 00:07:20 CET 2007

```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?

?cumsum

X <- runif(20)

sumr.1(X)
[1] 0.6359909 0.9435293 1.2167988 1.6229179
[5] 2.2816672 3.2687057 4.1973724 4.4421475
[9] 4.5601287 4.7500524 5.0639924 5.5831643
[13] 6.5071247 6.9861566 7.0352500 7.6723079
[17] 7.8560394 7.9281423 8.4757938 8.9985340

sumr.2(X)
[1] 0.6359909 0.9435293 1.2167988 1.6229179
[5] 2.2816672 3.2687057 4.1973724 4.4421475
[9] 4.5601287 4.7500524 5.0639924 5.5831643
[13] 6.5071247 6.9861566 7.0352500 7.6723079
[17] 7.8560394 7.9281423 8.4757938 8.9985340

cumsum(X)
[1] 0.6359909 0.9435293 1.2167988 1.6229179
[5] 2.2816672 3.2687057 4.1973724 4.4421475
[9] 4.5601287 4.7500524 5.0639924 5.5831643
[13] 6.5071247 6.9861566 7.0352500 7.6723079
[17] 7.8560394 7.9281423 8.4757938 8.9985340

all(cumsum(X) == sumr.1(X))
[1] TRUE

> Cheers,
> Alexy
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.

--
Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894

```