Search code examples
rcumsum

cumsum() from last entry and moving backward


I want to calculate cumulative sum of a vector of numbers from the last value and moving backward. the standard cumsum() function in R generally start from the first value and move forward as in simple example -

cumsum(1:5)
## 1  3  6 10 15

But I want a result like -

15, 14, 12, 9, 5

Is there any R function to directly calculate that?


Solution

  • the solution you are looking for is:

    rev(cumsum(rev(x)))