Another way:
idx <- which(data$B == 1) sum(data$A[idx[idx == (seq_along(idx) + idx[1] - 1)]])
Idea: first get all the indices 1. Here it is c(2,3,5) . From the very beginning, index = "2" you want to get all indexes that are continuous (or sequentially, that is, c(2,3,4,5...) ). So, from 2 take this many consecutive numbers and equate them. They will not be equal at the moment when they are not continuous. That is, when there is a mismatch, all the other following numbers will also have a mismatch. Thus, the first few numbers for which a match is equal will only be those that are “consecutive” (this is what you want).
source share