# How to find the sum of a column values up to a value in another column in R?

R ProgrammingServer Side ProgrammingProgramming

#### Artificial Intelligence : The Future Of Programming

15 Lectures 54 mins

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

To find the sum of a column values up to a particular value in another column, we can use cumsum function with sum function.

For example, if we have a data frame called df that contains two columns say x and y and we want to find the sum of x values until y is equal to 2 then we can use the following command −

sum(df$x[cumsum(df$y==2)==0])

## Example 1

Following snippet creates a sample data frame −

x1<-rpois(20,5)
x2<-rpois(20,2)
df1<-data.frame(x1,x2)
df1

## Output

The following dataframe is created −

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

To find the sum of x1 until x2 reached 0, add the following code to the above snippet −

x1<-rpois(20,5)
x2<-rpois(20,2)
df1<-data.frame(x1,x2)
sum(df1$x1[cumsum(df1$x2==0)==0])

## Output

If you execute all the above given snippets as a single program, it generates the following output −

 67


## Example 2

Following snippet creates a sample data frame −

y1<-round(rnorm(20),1)
y2<-round(rnorm(20),1)
df2<-data.frame(y1,y2)
df2

## Output

The following dataframe is created −

    y1    y2
1   2.4  -0.7
2   0.1   2.7
3  -0.7   0.0
4   1.6  -1.9
5   0.2  -1.0
6   0.2   1.7
7   0.7   0.7
8  -0.1  -0.3
9  -0.2  -0.2
10 -1.3   1.4
11 -2.5  -0.4
12  1.2   0.9
13  0.8  -0.4
14  0.8  -1.3
15  0.6   0.5
16 -0.8  -1.8
17  0.4  -0.4
18  0.4   0.6
19 -1.0   0.2
20  0.3   0.6

To find the sum of y1 until y2 reached 0.5, add the following code to the above snippet −

y1<-round(rnorm(20),1)
y2<-round(rnorm(20),1)
df2<-data.frame(y1,y2)
sum(df2$y1[cumsum(df2$y2==0.5)==0])

## Output

If you execute all the above given snippets as a single program, it generates the following output −

 3.2