1

Assume I have a vector containing the following values:

foo <- c(1:5)
[1] 1 2 3 4 5 

Is there a function or otherwise quick way to get each value of foo to add recursively to the numbers before it?

Desired Result is a vector containing these added values:

1 3 6 10 15
  • foo[1] is 1, foo[1] + foo[2] is 1 + 2 = 3, foo[1] + foo[2] + foo[3] is 1 + 2 + 3 = 6, etc.

My attempt:

I came up with:

vapply(1:length(foo), function(x) sum(foo[1]:foo[x]),integer(1))

But I'm hoping there is a simpler way to do this...

theforestecologist
  • 4,667
  • 5
  • 54
  • 91

1 Answers1

1

Yes, cumsum does exactly that:

cumsum(foo)
# [1]  1  3  6 10 15

Another handy and closely related function is cumprod(x) for cumulative products. See ?cumsum.

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
  • Exactly what I needed. Thanks! Out of curiosity, how does `cumsum` work? I looked [here](https://svn.r-project.org/R/trunk/src/library/base/man/cumsum.Rd), but the linked description doesn't include the underlying *functional* code (i.e., what the function is *actually doing*) – theforestecologist Mar 15 '18 at 20:52
  • 1
    @theforestecologist, that's because *.Rd are just documentation files. See the first function in https://svn.r-project.org/R/trunk/src/main/cum.c – Julius Vainora Mar 15 '18 at 20:58
  • And the downvote is for...? – Julius Vainora Mar 16 '18 at 23:18