I'm looking for a computationally efficient way to find local maxima/minima for a large list of numbers in R. Hopefully without for
loops...
For example, if I have a datafile like 1 2 3 2 1 1 2 1
, I want the function to return 3 and 7, which are the positions of the local maxima.
When a function's slope is zero at x, and the second derivative at x is: less than 0, it is a local maximum. greater than 0, it is a local minimum.
Correct answer: To find the local maximum, we must find where the derivative of the function is equal to 0. Given that the derivative of the function yields using the power rule . We see the derivative is never zero. However, we are given a closed interval, and so we must proceed to check the endpoints.
To find the local minimum of any graph, you must first take the derivative of the graph equation, set it equal to zero and solve for . To take the derivative of this equation, we must use the power rule, . We also must remember that the derivative of a constant is 0.
diff(diff(x))
(or diff(x,differences=2)
: thanks to @ZheyuanLi) essentially computes the discrete analogue of the second derivative, so should be negative at local maxima. The +1
below takes care of the fact that the result of diff
is shorter than the input vector.
edit: added @Tommy's correction for cases where delta-x is not 1...
tt <- c(1,2,3,2,1, 1, 2, 1) which(diff(sign(diff(tt)))==-2)+1
My suggestion above ( http://statweb.stanford.edu/~tibs/PPC/Rdist/ ) is intended for the case where the data are noisier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With