3
The problem can be solved with a trick diff/cumsum
, that gives vector segments a
which comply with the condition, followed by ave/seq_along
, to give integer sequences. And to put zeros in the right places, multiply this result by the condition f
.
f <- a > 100
g <- cumsum(c(FALSE, diff(f) != 0))
b <- ave(g, g, FUN = seq_along)
res <- cbind(a, b = b * f)
head(res, 15)
# a b
# [1,] 87.49 0
# [2,] 96.35 0
# [3,] 232.70 1
# [4,] 141.15 2
# [5,] 282.40 3
# [6,] 150.45 4
# [7,] 111.85 5
# [8,] 175.59 6
# [9,] 118.41 7
#[10,] 122.31 8
#[11,] 72.02 0
#[12,] 195.78 1
#[13,] 251.33 2
#[14,] 204.64 3
#[15,] 241.09 4