This problem is very similar to Consecutive value after column value change in R
So for
SOG <- c(4,4,0,0,0,3,4,5,0,0,1,2,0,0,0)
You can try my TrueSeq function from my GitHub-only "SOfun" package.
Usage would be:
library(SOfun)
TrueSeq(as.logical(SOG))
# [1] 1 1 0 0 0 2 2 2 0 0 3 3 0 0 0
To get the inverse, just negate the as.logical
step:
TrueSeq(!as.logical(SOG))
# [1] 0 0 1 1 1 0 0 0 2 2 0 0 3 3 3
Assuming you mean a "group of SOG" is a set of consecutive non-zero SOG values, i.e. starts with a non-zero SOG value and ends with a non-zero SOG value (not necessarily the same value):
Trips <- ifelse(SOG>0, cumsum(c(SOG[1]>0, diff(SOG>0)) == 1), 0)
# [1] 1 1 0 0 0 2 2 2 0 0 3 3 0 0 0
This is one option:
replace(cumsum(c(SOG[1], abs(diff(SOG))) == SOG & SOG != 0), SOG == 0, 0)
# [1] 1 1 0 0 0 2 2 2 0 0 3 3 0 0 0