Skip to content

Instantly share code, notes, and snippets.

@dsparks
Forked from ramhiser/find_peaks.r
Created April 5, 2013 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsparks/5319108 to your computer and use it in GitHub Desktop.
Save dsparks/5319108 to your computer and use it in GitHub Desktop.
#' Finds the local maxima (peaks) in the given vector after smoothing the data
#' with a kernel density estimator.
#'
#' First, we smooth the data using kernel density estimation (KDE) with the
#' \code{\link{density}} function. Then, we find all the local maxima such that
#' the density is concave (downward).
#'
#' Effectively, we find the local maxima with a discrete analogue to a second
#' derivative applied to the KDE. For details, see this StackOverflow post:
#' \url{http://bit.ly/Zbl7LV}.
#'
#' @param x numeric vector
#' @param ... additional arguments passed to the \code{\link{density}} function
#' @return a vector containing the peaks
find_peaks <- function(x, ...) {
x <- as.vector(x)
dens <- density(x, ...)
second_deriv <- diff(sign(diff(dens$y)))
dens$x[which(second_deriv == -2) + 1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment