title: Finding local maxima and minima in R
body: <p>I'm trying to create a function to find a "maxima" and "minima". I have the following data:</p>
  
  <pre><code>  y
    157
    144
     80
    106
    124
     46
    207
    188
    190
    208
    143
    170
    162
    178
    155
    163
    162
    149
    135
    160
    149
    147
    133
    146
    126
    120
    151
     74
    122
    145
    160
    155
    173
    126
    172
     93
  </code></pre>
  
  <p>I have tried this function to find "maxima"</p>
  
  <pre><code>localMaxima &lt;- function(x) {
    # Use -Inf instead if x is numeric (non-integer)
    y &lt;- diff(c(-.Machine$integer.max, x)) &gt; 0L
    rle(y)$lengths
    y &lt;- cumsum(rle(y)$lengths)
    y &lt;- y[seq.int(1L, length(y), 2L)]
    if (x[[1]] == x[[2]]) {
      y &lt;- y[-1]
    }
    y
  }
  
  maks &lt;- localMaxima(x)
  </code></pre>
  
  <p>And funtion to find "minima"</p>
  
  <pre><code>localMinima &lt;- function(x) {
        # Use -Inf instead if x is numeric (non-integer)
        y &lt;- diff(c(.Machine$integer.max, x)) &gt; 0L
        rle(y)$lengths
        y &lt;- cumsum(rle(y)$lengths)
        y &lt;- y[seq.int(1L, length(y), 2L)]
        if (x[[1]] == x[[2]]) {
          y &lt;- y[-1]
        }
        y
      }
  
      mins &lt;- localMinima(x)
  </code></pre>
  
  <p>And the result is not 100% right</p>
  
  <pre><code>maks = 1  5  7 10 12 14 16 20 24 27 31 33 35
  mins = 3  6  8 11 13 15 19 23 26 28 32 34 36
  </code></pre>
  
  <p>The result should</p>
  
  <pre><code>maks = 5  7 10 12 14 16 20 24 27 31 33 35
  mins = 3  6  8 11 13 15 19 23 26 28 32 34
  </code></pre>
  
  <p><a href="https://stackoverflow.com/questions/6836409/finding-local-maxima-and-minima">Finding local maxima and minima in R</a> comes close, but doesn't quite fit.</p>
  
  <p>How can I fix this?</p>
  
  <p>Thanks you very much</p>