I have not enough reputation to comment direcly on stas-g's answer but this is a comment on an issue i found with stas-g's code
I have vectors with incomplete data
a = c(1.60676107, -1.84154137, -0.03814237, -3.01587711, 6.67004912, NA, NA, -0.94917515)
# Looking at the data find_peaks(a, m=3) should return 5
# and find_peaks(-a, m= 3) should return 4
find_peaks(a, m = 3)
# returns numeric(0) with the code as is
find_peaks(-a, m)
# returns an error
The error is due to the evaluation of the all condition
if(all(x[c(z : i, (i + 2) : w)] <= x[i + 1])) return(i + 1) else return(numeric(0))
In the first case the term to evaluate by all() returns FALSE before reaching NA
and find_peaks(-a) fails because the all() returns NA and if(NA) fails.
However adding na.rm = T to all()
if(all(x[c(z : i, (i + 2) : w)] <= x[i + 1], na.rm = T)) return(i + 1) else return(numeric(0))
does not solve the issue. find_peaks(-a,m=3) returns 4 but find_peaks(a, m = 3) returns numeric(0) again instead of 5
Padding NA with the last valid value before NA will add a local extremum to the results and find_peaks(a, m= 3) returns 5 and 7
The c++ function by caseyk does return 4 and 5 as we would expect from visual observation
findPeaks
appears in my reply, @Adam. BTW, the package is "quantmod". $\endgroup$