Created
June 21, 2013 14:55
-
-
Save jamiefolson/5831746 to your computer and use it in GitHub Desktop.
Finding local maxima and minima in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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