[R] Need some vectorizing help
David Winsemius
dwinsemius at comcast.net
Thu Nov 24 16:35:42 CET 2011
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]]
> [1]; }, v)
> ;
> find the next crossing
> out <- data.frame(peak=L,Return=R)
> out
> }
>
> Thanks in advance!
>
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list