df <- cbind(c(1,1,1,1,1,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,5,5,5,5), c(6,12,18,24,30,3,9,21,6,12,18,24,30,36,6,12,18,24,30,36,12,24,36,48), c(0.4,1.5,2.7,1.6,0.4,1.3,3.1,3.6,0.5,2.6,3.7,1.8,0.9,0.3,0.7,1.6,1.3,2.8,1.9,1.8,2.0,1.0,3.0,0.8))
colnames(df) <- c("ID","time","value")
I have a dataset as given by the code above. I would like to know that for each ID, starting from the lowest/starting time, if the value bounced up by at least 2 compared to the lowest value before the rise and then went down below or equal to the lowest pre-bounce value. I would like to flag the time of the increase by at least 2 as the time of bounce.
So for example, in the above dataset, for ID 1, the lowest value was 0.4 at time 6 before it started rising. At time 18 it met the pre-defined threshold of 2 and then at time 30, it went down to a value equal to the pre-bounce lowest value. So I would like to flag ID 1 has having bounce and time 18 as the time for bounce.
On the other hand, for ID 2, although it rose at least by a value 2 (1.3-->3.6), never went back to a value below or equal to 1.3
For ID 3, it again met the criteria for bounce (0.5-->2.6-->3.7-->1.8-->0.9-->0.3). So I would like to flag ID 2 as having bounce and month 18 as the time for bounce.
For ID 4, although there was a rise by at least 2 i.e. from 0.7-->1.6-->1.3-->2.8 (at time 24), however, later on it never went down below 0.7 the lowest value before having the bounce. So it cannot be flagged as having bounce.
For ID 5, the values were 2-->1-->3-->0.8, so there was a bounce by at least 2 (1-->3) and then a fall to a value below the lowest pre-bounce value (0.8 <1.0). So this ID should be flagged as having a bounce and the time of bounce should be time 36.
Please help me with this dynamic calculation and also explain the codes if possible so that I can understand the concept. Thank you in advance.