Jung Song
Jung Song

Reputation: 11

Sum specific range in R

I want to sum A column using B column as criteria.

A B C

1
2
3
4 TRUE 10

5
6
7 TRUE 18

8
9
10 TRUE 27

10 in C column is sum(1,2,3,4) 18 is sum(5,6,7) 27 is sum(10,9,8)

Upvotes: 1

Views: 642

Answers (2)

BENY
BENY

Reputation: 323266

Same function ave , but different idea to get the group function .

ave(df1$A,cumsum(c(F,diff(df1$B)==-1)),FUN=cumsum)
 [1]  1  3  6 10  5 11 18  8 17 27

Upvotes: 1

Rui Barradas
Rui Barradas

Reputation: 76432

A simple application of ave with groups defined by a variable computed by a cumsum trick will do what you want.

ave(df1$A, rev(cumsum(rev(df1$B))), FUN = cumsum)
#[1]  1  3  6 10  5 11 18  8 17 27

Data.

df1 <- read.table(text = "
A B C
1 FALSE 1
2 FALSE 3
3 FALSE 6
4 TRUE 10
5 FALSE 5
6 FALSE 11
7 TRUE 18
8 FALSE 8
9 FALSE 17
10 TRUE 27                  
", header = TRUE)

Upvotes: 1

Related Questions