Use 'rle': > x <- rle(sample[,2]) > x Run Length Encoding lengths: int [1:9] 10 3 3 1 1 1 1 17 3 values : num [1:9] 0 1 0 1 0 1 0 1 0 > which.max(x$lengths[x$values==1]) [1] 4 > which.max(x$lengths * x$values) # makes use of the fact you are only using 0 > & 1 [1] 8 > cumsum(c(1, x$lengths)) [1] 1 11 14 17 18 19 20 21 38 41 > cumsum(c(1, x$lengths))[8] # index of the start of the run [1] 21 > x$lengths[8] # length of the run [1] 17 >
On Wed, Oct 28, 2009 at 12:27 PM, Staples, Angela Dawn <[email protected]> wrote: > I need to determine the length of the longest series of consecutive numbers > (1's to be specific) and the start time of that series. For example, in the > following sample, the first column is "time" and the second column indicates > the presence of the target behavior. > > I would like a function that would return "21" as the start time and "17" as > the length. > > sample <- > matrix(data=c(1:40,rep(0,10),rep(1,3),rep(0,3),1,0,1,0,rep(1,17),0,0,0),40,2 > ) > > I would appreciate any suggestions you have. > > Respectfully, > ~ Angela > > ______________________________________________ > [email protected] mailing list > 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. > -- Jim Holtman Cincinnati, OH +1 513 646 9390 What is the problem that you are trying to solve? ______________________________________________ [email protected] mailing list 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.

