I think that the rle() function may help you to tackle the problem in a more general way.
https://stat.ethz.ch/R-manual/R-devel/library/base/html/rle.html Using William's suggested series: x <- c(2,2,3,4,4,4,4,5,5,5,3,1,1,0,0,0,1,1,1) > x [1] 2 2 3 4 4 4 4 5 5 5 3 1 1 0 0 0 1 1 1 rle.x <- rle(x) rle.x Run Length Encoding lengths: int [1:8] 2 1 4 3 1 2 3 3 values : num [1:8] 2 3 4 5 3 1 0 1 And then you can apply diff() to rle.x$values while keeping in mind the run lengths (rle.x$lengths). Good luck, -- GG [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.