I would do it this way:
dat[, newCol := rleid(FixationSaccade), by = .(Trial)]
dat[FixationSaccade == 'F', newCol := NA]
dat[FixationSaccade == 'S', newCol := rleid(newCol), by = .(Trial)]
# > dat
# Trial FixationSaccade newCol
# 1: 1 F NA
# 2: 1 F NA
# 3: 1 S 1
# 4: 1 S 1
# 5: 1 F NA
# 6: 1 F NA
# 7: 1 S 2
# 8: 1 S 2
# 9: 2 F NA
# 10: 2 F NA
# 11: 2 S 1
# 12: 2 S 1
# 13: 2 F NA
# 14: 2 F NA
# 15: 2 S 2
# 16: 2 S 2
Or with a customized version of rleid
:
rleid2 <- function(x){
r <- rle(x)
y <- cumsum(r$values == 'S')
y[r$values == 'F'] <- NA
r$values <- y
inverse.rle(r)
}
dat[, newCol2 := rleid2(FixationSaccade), by = .(Trial)]
# Trial FixationSaccade newCol newCol2
# 1: 1 F NA NA
# 2: 1 F NA NA
# 3: 1 S 1 1
# 4: 1 S 1 1
# 5: 1 F NA NA
# 6: 1 F NA NA
# 7: 1 S 2 2
# 8: 1 S 2 2
# 9: 2 F NA NA
# 10: 2 F NA NA
# 11: 2 S 1 1
# 12: 2 S 1 1
# 13: 2 F NA NA
# 14: 2 F NA NA
# 15: 2 S 2 2
# 16: 2 S 2 2
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…