R function for calculating a 'cumulative difference'

Viewed 437

I have a vector like

v <- c(76, 31, 33, 7)

and need to calculate its 'cumulative difference' resulting in

cumdiff <- c(45, 12, 5)

which is 76 - 31 = 45 and 45 - 33 = 12 and 12 - 7 = 5.

Is there an R function like cumsum or do I need to use a loop?

Thank you very much for your help on this.

2 Answers

An option using Reduce:

Reduce(`-`, v, accumulate=TRUE)[-1L]
#[1] 45 12  5

Or using negative of cumsum

v[1L] - cumsum(v[-1L])

We can also use accumulate from purrr

library(purrr)
accumulate(v, `-`)[-1]
#[1] 45 12  5
Related