Search code examples
rdifferencecumsum

R function for calculating a 'cumulative difference'


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.


Solution

  • An option using Reduce:

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

    Or using negative of cumsum

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