Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional way to reverse cumulative sum?

Tags:

r

If I have a vector of a cumulative sum, e.g.

> vec <- cumsum(1:10) [1]  1  3  6 10 15 21 28 36 45 55 

is there a functional way to translate vec into it's original vector of c(1:10)?

Right now, I'm using a for-loop that goes:

> result <- vec[1] > for (i in 2:length(vec)) result <- append(result, vec[i]-vec[i-1]) > result [1]  1  2  3  4  5  6  7  8  9 10 

But that doesn't seem very R like to me... Any ideas?

like image 615
Riaan Avatar asked Jan 28 '14 22:01

Riaan


People also ask

What is a reverse cumulative sum?

Returns a vector of cumulative sums of the input values, running in reverse order.

How do you reverse a cumulative sum in R?

Reverse cumulative sum of a column is calculated using rev() and cumsum() function. cumsum() function takes up column name as argument which computes the cumulative sum of the column and it is passed to rev() function which reverses the cumulative sum as shown below.

What is cumulative sum formula?

A running total, or cumulative sum, is a sequence of partial sums of a given data set. It is used to show the summation of data as it grows with time (updated every time a new number is added to the sequence).

Why do we calculate cumulative sum?

Cumulative sums, or running totals, are used to display the total sum of data as it grows with time (or any other series or progression). This lets you view the total contribution so far of a given measure against time.


1 Answers

Just use diff to get the successive differences:

> c(vec[1],diff(vec))  [1]  1  2  3  4  5  6  7  8  9 10 
like image 152
joran Avatar answered Oct 13 '22 03:10

joran