Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating cumulative sum for each row

Tags:

r

I am trying to calculate the cumulative sum for each row using the following code:

df <- data.frame(count=1:10)  for (loop in (1:nrow(df)))     {df[loop,"acc_sum"] <- sum(df[1:loop,"count"])} 

But I don't like the explicit loop here, how can I modify it?

like image 382
lokheart Avatar asked Sep 26 '11 03:09

lokheart


People also ask

What is cumulative sum example?

The definition of the cumulative sum is the sum of a given sequence that is increasing or getting bigger with more additions. The real example of a cumulative sum is the increasing amount of water in a swing pool. Example: Input: 10, 15, 20, 25, 30. Output: 10, 25, 45, 70, 100.


1 Answers

You want cumsum()

df <- within(df, acc_sum <- cumsum(count)) 
like image 94
Chase Avatar answered Sep 25 '22 00:09

Chase