Skip to content
Prev 206026 / 398513 Next

help needed to find zero areas in a vector

You can use the following functions, which return TRUE
for elements which are last (or first) in a run of equal
values and FALSE for other elements:
   lastInRun <- function(x)c(x[-1]!=x[-length(x)], TRUE)
   firstInRun <- function(x)c(TRUE, x[-1]!=x[-length(x)])
They are fast for long vectors but don't handle NA's.
E.g.,
   > x<-c(0,0,1,1,0,0,0,0,1,1,0,0,0,0)
   > data.frame(x, first=firstInRun(x), last=lastInRun(x))
      x first  last
   1  0  TRUE FALSE
   2  0 FALSE  TRUE
   3  1  TRUE FALSE
   4  1 FALSE  TRUE
   5  0  TRUE FALSE
   ...
   14 0 FALSE  TRUE
If you are only interested only in runs of 0's use
   firstInRun(x) & x==0
to flag elements of x that start a run of zeros.

For many things the logical vector output will suffice
but you can use which(logical) to convert it to the
equivalent integer indices.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com