Skip to content

patterns in numeric vector

1 message · Bert Gunter

#
Oops  -- neglected to cc the list. Also note the correction at the
end, changing "starts" to "begins".

-- Bert
On Mon, Jun 20, 2016 at 2:33 PM, Bert Gunter <bgunter.4567 at gmail.com> wrote:
Thanks for the reproducible example -- it made your meaning clear.

This is the sort of thing for which rle() is useful. If you go through
the following step by step it should be clear what's going on.

 z<-c(7,223,42,55,30,25,61,5,70)
x <- 40
rl <- rle( z < x)  ## runs of TRUE and FALSE (logicals)
## Note that you may wish to change this to <=

lens <- rl$lengths    ## lengths of runs
ends <- cumsum(lens)   ##  indices where the runs end
begins <- c(1,ends[-length(ends)]+1)  ## indices where the runs begin

## now use logical indexing to pick out only the runs meeting the
condition that  z < x
vals <- rl$values
begins[vals]
ends[vals]


Note: This is the sort of query for which someone cleverer than I may
have a simpler or more efficient solution. If so, please post it so I
and others can learn from it.

 Cheers,
 Bert



 Bert Gunter

 "The trouble with having an open mind is that people keep coming along
 and sticking things into it."
 -- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )