local maxima in data frame

Hi all
i am trying to find several local maximas for each subject in a dataframe for a specific variable,
is there a function that could do that?
for instance if i use max() i will get the highest value for each subject, so is there a similar function for peak or local maxima?

thank you

what is your definition of local ?

"Local maxima/minima" is typically used to describe a property of a continuous function with lots of peaks and valleys. I wouldn't use it to describe the maxes or mins in data.

Sounds like you just want to aggregate with a max. With the tidyverse, you'd use a group_by and summarize like this

iris %>% group_by(Species) %>% summarize_if(is.numeric, max)
#> # A tibble: 3 x 5
#>   Species    Sepal.Length Sepal.Width Petal.Length Petal.Width
#> * <fct>             <dbl>       <dbl>        <dbl>       <dbl>
#> 1 setosa              5.8         4.4          1.9         0.6
#> 2 versicolor          7           3.4          5.1         1.8
#> 3 virginica           7.9         3.8          6.9         2.5

Created on 2021-07-05 by the reprex package (v1.0.0)

thank you for your response,
i use the local maxima or minima to analyse ERP waveforms which behave in some case like sin or cos
i will try what you have suggested. thank you

local maxima for example is a not the most maximum peak, it is a maximum but there are also other maximum peaks.

I think what @nirgrahamuk wants to know is how well separated local maxima need to be, probably both horizontally and vertically. For example, how many local maxima are in this plot.

#> Warning: package 'ggplot2' was built under R version 4.0.5

DF <- data.frame(Values = c(15,15,15,16,14,14,15,24,20,55,50,56,37,32,39,60,59,25,17,14,15,15,17,14,
ggplot(DF, aes(x = 1:34, y = Values)) + geom_point() + geom_line()

Created on 2021-07-05 by the reprex package (v0.3.0)

You might do a spline fit and return the function with splinefun and then use that function to find local maxima by either finding the zeros in the derivative with fderiv and fsolve, or performing gradient based optimizations with nloptr.

How about a package that calculates numerical derivatives? https://cran.r-project.org/web/packages/numDeriv/numDeriv.pdf and numderiv function - RDocumentation are two . Of course, f'(x) = 0 does not guarantee a local maxima or minima.

Thank you a lot, i will look into these packages, seems that this will work

I don't recommend taking the numerical derivative of the data itself. This will produce a derivative value at every point, but you'll have no way of identifying if the function will reach exactly zero in that region. That's why you might want to do a spline fit first and use the splinefun to differentiate.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.