Finding local maxima and minima

前端 未结 14 1870
说谎
说谎 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:05

    Finding local maxima and minima for a not so easy sequence e.g. 1 0 1 1 2 0 1 1 0 1 1 1 0 1 I would give their positions at (1), 5, 7.5, 11 and (14) for maxima and 2, 6, 9, 13 for minima.

    #Position                1 1 1 1 1
    #      1 2 3 4 5 6 7 8 9 0 1 2 3 4
    x <- c(1,0,1,1,2,0,1,1,0,1,1,1,0,1) #Frequency
    #      p v     p v  p  v   p   v p  p..Peak, v..Valey
    
    peakPosition <- function(x, inclBorders=TRUE) {
      if(inclBorders) {y <- c(min(x), x, min(x))
      } else {y <- c(x[1], x)}
      y <- data.frame(x=sign(diff(y)), i=1:(length(y)-1))
      y <- y[y$x!=0,]
      idx <- diff(y$x)<0
      (y$i[c(idx,F)] + y$i[c(F,idx)] - 1)/2
    }
    
    #Find Peaks
    peakPosition(x)
    #1.0  5.0  7.5 11.0 14.0
    
    #Find Valeys
    peakPosition(-x)
    #2  6  9 13
    
    peakPosition(c(1,2,3,2,1,1,2,1)) #3 7
    

提交回复
热议问题