I was wondering if there would be the possibility to identify the position of the range values according to a condition. This condition is determined by the longest sequence of values lower than 3.
For instance,
x <- c(4, 1, 2, 1, 1, 4, 1, 1, 1, 1, 2, 1, 1, 1, 1, 4, 1, 1)
Desired output:
c(7:15)
It may be that split()
and rle()
could be useful in this case but any help will be more than helpful.
CodePudding user response:
You could do the rle
on x < 3
, then find which
of the TRUE
s is max
. Then sum
the lengths before the match plus one as well as the match itself (which will be the final position). Finally do a seq
uence with the values.
rl <- rle(x < 3)
w <- which(rl$lengths == max(rl$lengths) & rl$values)
do.call(seq.int, list(sum(rl$lengths[1:(w - 1)]) 1, sum(rl$lengths[1:w])))
# [1] 7 8 9 10 11 12 13 14 15