'"Residence time" in interval

The title sounds a bit strange, but it hits the question - I want to find that index of a vector x from which a time series no longer leaves a certain interval [z-a,z+a]. If I use

which(x < z+a & x > z-a)

then I get all cases where a value lies in this interval, but it could also be that it leaves the interval again in the meantime. Is there a direct and quick way to find the index of x from which all values lie in [z-a,z+a]?

EDIT:

okay... example

x = c(1,2,3,4,5,6,7,4,9.7,10,4,4,4,4,3,3,3,8,8,8,8,8,8,9.6,9.6,9.8,9.9,9.9)

interval: [9.5,10]

r


Solution 1:[1]

x = c(1,2,3,4,5,6,7,4,9.7,10,4,4,4,4,3,3,3,8,8,8,8,8,8,9.6,9.6,9.8,9.9,9.9)

library(data.table)
y <- rle(between(x, 9.5, 10))
# Run Length Encoding
# lengths: int [1:4] 8 2 13 5
# values : logi [1:4] FALSE TRUE FALSE TRUE

ifelse( 
  #check if laste sequence contains TRUE
  last(y$values), 
  #if so then find the start position of the last sequence
  length(x) - last(y$lengths), 
  #if not then
  "there is no such index" )

# [1] 23

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wimpel