Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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{}.
#' @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
You can’t perform that action at this time.