I have the following dataframe:
time <- c(1,2,3,4,5,6,7,8,9,10,11,12)
threshold <- c(1,1,1,0,0,2,2,1,1,2,2,0)
value <- c(5,3,2,4,6,9,1,10,3,5,2,4)
df <- data.frame(time, threshold, value)
The logic behind the threshold variable is that when there is a 1: store the first value (5) and subtract the number when the threshold changes (4). During the first threshold period of "1", the calculation would be 5 - 4 = 1, which should be stored in a new column at time t=4.
Threshold "0" means no calculation.
Threshold "2" means just the reverse of "1", where the the initial value 9 is subtracted by 10.
The goal would be a table like this:

Is there a way to calculate perform this calculation in R?