Skip to content

Max consecutive increase in sequence

4 messages · Marko Milicic, Ingmar Visser, Tony Plate +1 more

#
rle(diff(sq)) could be helpful here,
best, Ingmar
On May 13, 2008, at 11:19 PM, Marko Milicic wrote:

            
#
If the increases or decreases could be any size, 
rle(sign(diff(x))) could do it:

 > x <- c(1, 2, 3, 4, 4, 4, 5, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1)
 > r <- rle(sign(diff(x)))
 > r
Run Length Encoding
   lengths: int [1:5] 3 2 2 5 4
   values : num [1:5] 1 0 1 -1 0
 > i1 <- which(r$lengths==max(r$lengths[r$values==1]) & 
r$values==1)[1]
 > i2 <- which(r$lengths==max(r$lengths[r$values==-1]) & 
r$values==-1)[1]
 > i1
[1] 1
 > i2
[1] 4
 > rbind(up=c(start=cumsum(c(1, r$lengths))[i1], 
len=r$lengths[i1]), down=c(start=cumsum(c(1, 
r$lengths))[i2], len=r$lengths[i2]))
      start len
up       1   3
down     8   5
 >
Ingmar Visser wrote:
#
I believe the original poster was looking for runs of consecutive
values.  Here's a generalization of Tony's solution:

findlong = function(seq){
     rr = rle(seq)
     lens = rr$length
     lens[rr$value == FALSE] = 0
     ll = which.max(lens)
     start = cumsum(c(1,rr$length))[ll]
     list(start=start,length=rr$lengths[ll])
}
Then
$start
[1] 1

$length
[1] 3
$start
[1] 8

$length
[1] 5

                                        - Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu
On Tue, 13 May 2008, Tony Plate wrote: