Skip to content

Need some vectorizing help

3 messages · Scott Tetrick, David Winsemius

#
So I have a problem that I'm trying to get through, and I just can't 
seem to get it to run very fast in R.

What I'm trying to do is to find in a vector a local peak, then the next 
time that value is crossed later.  I don't care about peaks that may be 
lower than this first one - they can be ignored.  I've tried some sapply 
methods along the way, but they all are slower.  The best solution I 
have is a loop, and I just know there are smart R folks that could help 
me eliminate it.

Peak2Return <- function(v) {
   Q <- (1:m)[diff(v)<0]                            ; find all the peaks
   L <- Q[c(TRUE,v[Q[-1]] > v[Q[-length(Q)]])]
                                                                    ; 
eliminate lower peaks
   R <- sapply(L,function (x,v) { ((x+1):length(v))[v[x] < 
v[(x+1):m]][1]; }, v)
                                                                     ; 
find the next crossing
   out <- data.frame(peak=L,Return=R)
   out
}

Thanks in advance!
#
On Nov 24, 2011, at 4:52 AM, Scott Tetrick wrote:

            
It looks as though you are reinventing hte function:

?cummax
David Winsemius, MD
West Hartford, CT
2 days later
#
Thank you very much David - R is so rich, the easy way can be hard to find.

Just to close this out for others, the final solution I used was:

Peak2Return <- function(v) {
   S <- cummax(v)
   L <- which((v ==S) & (diff(c(0,v)<0))
   R <- sapply(v[L], function(x,S) {which(x < S)[1]; }, S)

now you have L for the left index, and R for the corresponding right 
index.  If there is no right index due to the curve, the R value is NA.
On 11/24/2011 7:35 AM, David Winsemius wrote: