R function for calculating a 'cumulative difference'
Asked Answered
A

2

3

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.

Arsenide answered 1/6, 2020 at 8:9 Comment(0)
T
4

An option using Reduce:

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

Or using negative of cumsum

v[1L] - cumsum(v[-1L])
Thee answered 1/6, 2020 at 8:12 Comment(1)
Wow, thanks. That was very fast and works perfectly. Thanks, again!Arsenide
H
1

We can also use accumulate from purrr

library(purrr)
accumulate(v, `-`)[-1]
#[1] 45 12  5
Hour answered 1/6, 2020 at 20:17 Comment(1)
Thank you very much for sharing this helpful solution. Sorry for the late response. Too many other duties.Arsenide

© 2022 - 2024 — McMap. All rights reserved.