Create group ID for runs of non-zero values

You can try:

as.integer(factor(cumsum(value==0)*NA^(value==0)))
#[1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3

Using rle(). First create a new vector replacing the zeros with NA.

x <- match(value != 0, TRUE)
with(rle(!is.na(x)), {
    lv <- lengths[values]
    replace(x, !is.na(x), rep(seq_along(lv), lv))
})
# [1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3

You could also do this:

id <- (value>0)^NA
x <- rle(value>0)$lengths[c(TRUE, FALSE)]
id[!is.na(id)] <- rep(seq_along(x), times=x)

#[1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3

Tags:

R

Vector

Grouping