cumsum(x) and diff(x)

Likan Zhan · 2017-03-07

diff(x) returns a vector of length (length(x)-1) which contains the difference between one element and the next in a vector x.

cumsum(x) returns a vector of length equal to the length of x containing the sum of the elements in x

x <- c(1:10)
diff(x)
cumsum(x)
## [1] 1 1 1 1 1 1 1 1 1
##  [1]  1  3  6 10 15 21 28 36 45 55

The combination of cumsum and diff leads to different results, depending on the order in which the functions are executed:

cumsum(diff(x))
diff(cumsum(x))
## [1] 1 2 3 4 5 6 7 8 9
## [1]  2  3  4  5  6  7  8  9 10