Skip to content

Instantly share code, notes, and snippets.

@ramhiser
Last active July 2, 2021 06:08
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ramhiser/5316385 to your computer and use it in GitHub Desktop.
Save ramhiser/5316385 to your computer and use it in GitHub Desktop.
Find local maxima (peaks) in a vector
#' 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