Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Finding local maxima and minima in R with discrete values

$
0
0

I'm looking for a reproducible way to find the most recent local peak in a given series (and separately, the most recent trough). For the most part the answers here - Finding local maxima and minima work, with the exception of cases as below, I have used Tommy's answer from this link as it seems the most robust.

x <- c(0.4,0.5,0.5,0.4,0.4,0.3,0.3)

  localMaxima <- function(x) {
    # Use -Inf instead if x is numeric (non-integer)
    y <- diff(c(-Inf, x)) > 0L
    rle(y)$lengths
    y <- cumsum(rle(y)$lengths)
    y <- y[seq.int(1L, length(y), 2L)]
    if (x[[1]] == x[[2]]) {
      y <- y[-1]
    }
    y
  }

>localMaxima(x)
[1] 2

In this instance [1] 3 should be returned rather than 2, as this is the most recent point (with the most recent data point being the end of the vector). Reversing the vector with rev(x) will not work as there is no reliable way to determine whether the vector must be reversed.


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>