Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumulative difference In R

What is the opposite of cumsum() in R

a = c(2, 5, 8)
cumsum = c(2, 7, 15)
cumdiff = c(2, 3, 1)

Because 5-2 = 3 and 8-7 = 1.

Is there a package that can be used for this one in R?

like image 550
Lilac_Mimo Avatar asked Oct 21 '25 05:10

Lilac_Mimo


1 Answers

In base R:

cumdiff <- function(x) x - head(c(0, cumsum(x)), -1)
#cumdiff <- function(x) x - c(0, cumsum(x))[-(length(x) + 1)]

In dplyr, with lag and default = 0:

library(dplyr)
cumdiff <- function(x) x - lag(cumsum(x), default = 0)

Result:

a = c(2,5,8)
cumdiff(a)
#[1] 2 3 1
like image 97
Maël Avatar answered Oct 23 '25 18:10

Maël



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!