Finding local maxima and minima

前端 未结 14 1860
说谎
说谎 2020-11-22 07:24

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 exampl

14条回答
  •  死守一世寂寞
    2020-11-22 08:04

    @Ben's solution is pretty sweet. It doesn't handle the follwing cases though:

    # all these return numeric(0):
    x <- c(1,2,9,9,2,1,1,5,5,1) # duplicated points at maxima 
    which(diff(sign(diff(x)))==-2)+1 
    x <- c(2,2,9,9,2,1,1,5,5,1) # duplicated points at start
    which(diff(sign(diff(x)))==-2)+1 
    x <- c(3,2,9,9,2,1,1,5,5,1) # start is maxima
    which(diff(sign(diff(x)))==-2)+1
    

    Here's a more robust (and slower, uglier) version:

    localMaxima <- function(x) {
      # Use -Inf instead if x is numeric (non-integer)
      y <- diff(c(-.Machine$integer.max, 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
    }
    
    x <- c(1,2,9,9,2,1,1,5,5,1)
    localMaxima(x) # 3, 8
    x <- c(2,2,9,9,2,1,1,5,5,1)
    localMaxima(x) # 3, 8
    x <- c(3,2,9,9,2,1,1,5,5,1)
    localMaxima(x) # 1, 3, 8
    

提交回复
热议问题