Last active
July 2, 2021 06:08
-
-
Save ramhiser/5316385 to your computer and use it in GitHub Desktop.
Find local maxima (peaks) in a vector
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
#' 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