# [R] Need some vectorizing help

Scott Tetrick scotttetrick at frontier.com
Sat Nov 26 17:18:52 CET 2011

```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); }, 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:
>
> On Nov 24, 2011, at 4:52 AM, Scott Tetrick wrote:
>
>> 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.
>
> It looks as though you are reinventing hte function:
>
> ?cummax
>
>
>>
>> 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]]; }, v)
>>                                                                    ;
>> find the next crossing
>>  out <- data.frame(peak=L,Return=R)
>>  out
>> }
>>