Finding local maxima and minima

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

    I had some trouble getting the locations to work in previous solutions and came up with a way to grab the minima and maxima directly. The code below will do this and will plot it, marking the minima in green and the maxima in red. Unlike the which.max() function this will pull all indices of the minima/maxima out of a data frame. The zero value is added in the first diff() function to account for the missing decreased length of the result that occurs whenever you use the function. Inserting this into the innermost diff() function call saves from having to add an offset outside of the logical expression. It doesn't matter much, but i feel it's a cleaner way to do it.

    # create example data called stockData
    stockData = data.frame(x = 1:30, y=rnorm(30,7))
    
    # get the location of the minima/maxima. note the added zero offsets  
    # the location to get the correct indices
    min_indexes = which(diff(  sign(diff( c(0,stockData$y)))) == 2)
    max_indexes = which(diff(  sign(diff( c(0,stockData$y)))) == -2)
    
    # get the actual values where the minima/maxima are located
    min_locs = stockData[min_indexes,]
    max_locs = stockData[max_indexes,]
    
    # plot the data and mark minima with red and maxima with green
    plot(stockData$y, type="l")
    points( min_locs, col="red", pch=19, cex=1  )
    points( max_locs, col="green", pch=19, cex=1  )
    

提交回复
热议问题