'Finding the first trigger in a series and taking average from that point on

I hope this finds you well. I was hoping to get some help analyzing some code where I identify a series of trials based on the start trigger (but ignoring the immediate triggers that follow). In the example below I would like to find the first 1 in a series of 1's and take the average across the next three numbers in Value_1 and Value_2. It should then find the next start period (the 8th value with the next set of 1's) and again take the average for the following 3 values, and so on. Thank you for your help and I am happy to answer any questions.

df <- data.frame(Value_1 = c(1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10), Value_2 = c(10,2,3,4,5,6,7,8,10,10,1,2,3,4,5,6,7,8,9,10), Triggers = c(0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0))

In the updated_df example below I would like the code to be able to work through possible interruptions in the Trigger value (e.g., a 0 in list of 1) and find the first 1 in a group of 1's and possible zeros and take the average across the next four numbers in Value_1 and Value_2. It should then find the next start period (the 9th value with the next set of 1's and 0's) and again take the average for the following 4 values, and so on. Thank you for your help and I am happy to answer any questions.

updated_df <-df <- data.frame(
  Value_1 = c(1,2,3,3,4,5,6,7,8,9,9,10,1,2,3,4,5,6,7,8,9,9,10),
  Value_2 = c(10,2,3,3,4,5,6,7,8,10,10,10,1,2,3,4,5,6,6,7,8,9,10),
  Triggers = c(0,1,1,0,1,0,0,0,1,1,0,1,0,0,0,0,0,1,0,1,1,0,0)
)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source