Is there a function to spot the first value in a time-series that meets a certain conditon?

Viewed 91

Working with time-series (in R) and needing to find the first moment when a certain value starts to appear: I have to find the time in which two variables become stable. I will use temperature in this example because I think it is better understood:

  • I have a variable A and a variable B (temperature at point A and B). They become heated at a specific moment. After it, the temperature will slowly drop until the difference is the same (i.e., 0). But because of some external issues, the difference among these (I called it "C") does not always reach 0- sometimes becomes stabilized at other levels, or the stabilization is not perfect. However, I must find the times in which these get stable. Showing the first time a "0" appears may be wrong. I thought of using the statistical mode for low values and retrieve the first one to appear (i.e. the first moment in the time series the mode shows up). Do you think it's a good idea? Is there any package to do this?

  • I wish to know if there is a way I can easily spot where both temperatures get stabilized. This graph is only one example but I should repeat it for many data (i.e. other similar time-series). At the same time, I think I could smooth the graph by using an average-mean or a moving-mean, let me know if you have an opinion about it too. Thank you very much. :)

example of one graph I am working with here

1 Answers

If DF has three columns representing the three series values in ascending order of time then dif is the corresponding vector of the differences between the largest and smallest at each time point. From that we determine for each row the largest difference in the remainder of the series giving cum, define thresh as the 10% point of the cum series and set v (shown as vertical line) to the corresponding row number after which all values of cum are less than that value. (You may wish to use a different percent point or hard code thresh to a given value.)

In the absence of test data we use the first 3 columns of the built in mtcars data frame.

DF <- mtcars[1:3]

dif <- apply(DF, 1, function(x) diff(range(x)))
cum <- rev(cummax(rev(dif)))

thresh <- quantile(cum, 0.10)
v <- if (any(cum <= thresh)) which.max(cum <= thresh) else NA

matplot(DF, type = "o", pch = 20)
abline(v = v)

screenshot

Update

Have a revised a few times.

Related