[R] Need some vectorizing help

Scott Tetrick scotttetrick at frontier.com
Thu Nov 24 10:52:18 CET 2011


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!



More information about the R-help mailing list