cumsum() from last entry and moving backward

Viewed 144

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?

3 Answers

the solution you are looking for is:

rev(cumsum(rev(x)))

You can do:

Reduce(sum, 1:5, right = TRUE, accumulate = TRUE)

[1] 15 14 12  9  5

Another base R option

> v <- 1:5

> sum(v) - cumsum(c(0, head(v, -1)))
[1] 15 14 12  9  5
Related