Search code examples
rmathematical-optimization

Retrieve values of local maxima in R data table - already have column numbers


using this question's solution: Finding local maxima and minima I have been able to retrieve what seems to be a list of column numbers from my data table for local maxima. I also need to retrieve the value of that peak from the table. Preferably I would return a matrix or equivalent where each row contains the local peak values rather than the positions, as I already have the positions

so say using a vector ex_data <-c(1,3,2,2,1,3,5,4,2,1) I would want to get a vector saying (3,5). I already have the code below:

local_max <- function(x) {
which(diff(sign(diff(x)))==-2)+1}
local_max(ex_data)

which produces vector (2,7)


Solution

  • It's easy. Just use the index vector for subsetting.

    ex_data[local_max(ex_data)]