Search code examples
rdataframesumreverse

Is there a way to reverse a cumulative sum column in an R Data Frame?


I'm new to R, and dealing with a Date Frame. I'm looking for a way to create a new column, and populate it with the reverse of another column which contains a cumulative sum. I want the individual values added each time.

I have data that looks like this:

Cumulative Sum
0
4
9
18
33

I'd like to create a new column and populate it with the individual value, reversing the cumulative sum, something like the following:

Cumulative Sum Individual Value
0 0
4 4
9 5
18 9
33 15

Any and all help would be very much appreciated.


Solution

  • Use diff, which computes iterated differences.

    vec=c(0,4,9,18,33)
    c(0,diff(vec))
    [1]  0  4  5  9 15
    

    If you vector does not start with 0, just use diff(vec).