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?
"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
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
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.
library(ggplot2)
#> 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,
15,15,28,65,70,52,20,15,15,15))
ggplot(DF, aes(x = 1:34, y = Values)) + geom_point() + geom_line()
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.
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.