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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With