I have the following vector of temperatures (in ˚ C):
Temperature <- c(-3:3, 3:-3, rep(-3, 2), -2:-1, 1:3, 2:1, -1:-4)
I need to calculate the time (number of observations) elapsed since the last freeze event and I also need to calculate the number of observations elapsed since the last thaw event. Freeze events are marked by temperature transitions from positive to negative values, and thaw events are marked by temperature transitions from negative to positive values. The output should look like these vectors:
Time_Since_Last_Freeze <- c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2, 3)
Time_Since_Last_Thaw <- c(NA, NA, NA, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 1, 2, 3, 4, 5, 6, 7, 8)
I've seen a few similar questions on Stack Overflow but none of them are exactly what I need. What are some efficient ways to generate these two output vectors?