Skip to content
Prev 199925 / 398502 Next

partial cumsum

Note that the 2nd argument assigns a group number
based on the number of NA's prior to the current
position in the vector.  The odd repeated calls to
rev() are there to put the NA's at the ends of the
groups, instead of at the beginnings:
   > x <- c(1, 2, 3, NA, 5, 6, 7, 8, 9, 10)
   > rev(cumsum(rev(is.na(x))))
    [1] 1 1 1 1 0 0 0 0 0 0
A more natural way to do this is
   > cumsum(is.na(c(NA,x[-length(x)])))
    [1] 1 1 1 1 2 2 2 2 2 2

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com