# How to find the cumulative sum but restarts it if a value is 1 in R?

Sometimes we want to find the conditional cumulative sums and these conditions can be resetting the cumulative if a particular value occurs. For example, finding the cumulative sum of a variable frame but restarting the sum if 1 occurs. In R, we can do this with the help of with, ave and cumusum function as shown in the below examples.

## Example1

Consider the below data frame:

Live Demo

> ID<-1:20
> Ratings<-sample(0:2,20,replace=TRUE)
> df1<-data.frame(ID,Ratings)
> df1

## Output

 ID Ratings
1 1   0
2 2   2
3 3   0
4 4   0
5 5   0
6 6   2
7 7   1
8 8   0
9 9   1
10 10 2
11 11 2
12 12 1
13 13 1
14 14 0
15 15 0
16 16 2
17 17 0
18 18 0
19 19 1
20 20 0

Finding the cumulative sums and restarting if 1 occurs:

## Example

> df1<-with(df1,ave(Ratings,cumsum(Ratings==1),FUN=cumsum))
> df1

## Output

[1] 0 2 2 2 2 4 1 1 1 3 5 1 1 1 1 3 3 3 1 1

## Example2

Live Demo

> x<-1:20
> y<-sample(1:4,20,replace=TRUE)
> df2<-data.frame(x,y)
> df2

## Output

  x y
1 1 2
2 2 2
3 3 1
4 4 1
5 5 3
6 6 2
7 7 2
8 8 3
9 9 1
10 10 4
11 11 2
12 12 1
13 13 1
14 14 3
15 15 2
16 16 2
17 17 1
18 18 4
19 19 4
20 20 4

Finding the cumulative sums and restarting if 1 occurs:

## Example

> df2<-with(df2,ave(y,cumsum(y==1),FUN=cumsum))
> df2

## Output

[1] 2 4 1 1 4 6 8 11 1 5 7 1 1 4 6 8 1 5 9 13

Updated on: 23-Nov-2020

558 Views