Skip to content

Instantly share code, notes, and snippets.

@jamiefolson
Created June 21, 2013 14:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiefolson/5831746 to your computer and use it in GitHub Desktop.
Save jamiefolson/5831746 to your computer and use it in GitHub Desktop.
Finding local maxima and minima in R
#' 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)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment