[R] Seeking a more efficient way to find partition maxima

From: Talbot Katz <topkatz_at_msn.com>
Date: Mon, 7 Jan 2008 11:18:54 -0500

Hi.  

Suppose I have a vector that I partition into disjoint, contiguous subvectors. For example, let v = c(1,4,2,6,7,5), partition it into three subvectors, v1 = v[1:3], v2 = v[4], v3 = v[5:6]. I want to find the maximum element of each subvector. In this example, max(v1) is 4, max(v2) is 6, max(v3) is 7. If I knew that the successive subvector maxima would never decrease, as in the example, I could do the following:  

partiCmax <- function( values, seriesIdx ) {   # assume seriesIdx is increasing integer sequence beginning with 1, ending at less than or equal to length(values)   parti <- cbind( seriesIdx, c( ( seriesIdx[ -1 ] - 1 ), length( values ) ) )   return( cummax( values )[ parti[ , 2 ] ] )
}
   

The use of cummax makes that pretty efficient, but if the subvector maxima are not non-decreasing, it doesn't work. The following function works (at least it did on the examples I tried):  

partiMax <- function( values, seriesIdx ) {   # assume seriesIdx is increasing integer sequence beginning with 1, ending at less than or equal to length(values)   parti <- cbind( seriesIdx, c( ( seriesIdx[ -1 ] - 1 ), length( values ) ) )   return( sapply( ( 1:length(seriesIdx) ), function ( i ) {return( max( values[ parti[ i, 1 ]:parti[ i, 2 ] ] ) ) } ) )
}
   

but I figured someone out there could come up with something cleverer. Thanks!  


R-help_at_r-project.org 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. Received on Mon 07 Jan 2008 - 16:21:49 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 08 Jan 2008 - 00:30:05 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive