How can I get the index of the sample whose previous samples were consecutive in a window or range and were greater than a fixed threshold in groups?
In the below example, I need to find the time when I have consecutively 3 samples in a window that starts from 3rd element to the end of the array, and also whose speed is greater than 35 speed >= 35 group-wise
speed_threshold = 35
Group Time Speed
1 5 25 # Ignore first 3 elements
1 10 23 # Ignore first 3 elements
1 15 21 # Ignore first 3 elements
1 20 33 # Speed < 35
1 25 40 # Speed > 35
1 30 42 # Speed > 35
1 35 52 # Speed > 35
1 40 48 # <--- Return time = 40 as answer for Group 1 !
1 45 52
2 5 48 # Ignore first 3 elements
2 10 42 # Ignore first 3 elements
2 15 39 # Ignore first 3 elements
2 20 36 # Speed > 35
2 25 38 # Speed > 35
2 30 46 # Speed > 35
2 35 53 # <--- Return time = 35 as answer for Group 2 !
3 5 45 # Ignore first 3 elements
3 10 58 # <--- Return time = NA as answer for group 3 !
The solution I have tried is as follows using data.table -
df[, {above <- Speed[-(1:3)] > speed_thresh
ends <- which(above & rowid(rleid(above)) == 3)
.(Return_Time = Time[ends[1]+ 1])}
, Group]
The above solution removes the first three elements from the entire array, and not remove the first three elements in each group, how can I ignore the first three elements in each group and then find the consecutive integers exceeding the threshold?
Thanks in advance!
Note
Lines <- "Group Time Speed
1 5 25 # Ignore first 3 elements
1 10 23 # Ignore first 3 elements
1 15 21 # Ignore first 3 elements
1 20 33 # Speed < 35
1 25 40 # Speed > 35
1 30 42 # Speed > 35
1 35 52 # Speed > 35
1 40 48 # <--- Return time = 40 as answer for Group 1 !
1 45 52
2 5 48 # Ignore first 3 elements
2 10 42 # Ignore first 3 elements
2 15 39 # Ignore first 3 elements
2 20 36 # Speed > 35
2 25 38 # Speed > 35
2 30 46 # Speed > 35
2 35 53 # <--- Return time = 35 as answer for Group 2 !
3 5 45 # Ignore first 3 elements
3 10 58 # <--- Return time = NA as answer for group 3 !"
df <- read.table(text = Lines, header = TRUE)