public
Created

Finding local maxima and minima in R

  • Download Gist
peaks.R
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#' Find local maxima and minima in R
#' @param x numeric vector to search for peaks
#' @param partial whether or not to include partial peaks
#' at the beginning or end of the vector
#' @param decreasing whether to find peaks (the default)
#' or valleys
which.peaks <- function(x,partial=TRUE,decreasing=FALSE){
if (decreasing){
if (partial){
which(diff(c(TRUE,diff(x)<=0,FALSE))>0)
}else {
which(diff(diff(x)<=0)>0)
}
}else {
if (partial){
which(diff(c(TRUE,diff(x)>=0,FALSE))<0)
}else {
which(diff(diff(x)>=0)<0)
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.