PCdL PCdL - 1 year ago 75
R Question

Sum the first two elements of a vector and use the result to calculate the second element of the vector

I have a hypothetical vector which looks like this:

a.vec <- c(.5, .8, .7, .4, 1, .8, .3)

The resulting vector should start at .5 (the first value), then sum the first 2 elements (.5 + .8) of a.vec (=1.3), then use 1.3 and add .7, then use 2 and add .4 etc.

The resulting vector should look like this:

result.vec <- c(.5, 1.3, 2, 2.4, 3.4, 4.2, 4.5)

I have been searching quite a bit now, but can't figure it out.

Any help would be greatly appreciated.


Answer Source

Couldn't find a duplicate, so posting as answer:

This is called a cumulative sum, and the function you're looking form is cumsum(a.vec).

As always, see the help page for more details.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download