Skip to content

Instantly share code, notes, and snippets.

@swo
Created December 3, 2024 19:25
Show Gist options
  • Save swo/19a1be6d7d6c881775964ffde7620894 to your computer and use it in GitHub Desktop.
Save swo/19a1be6d7d6c881775964ffde7620894 to your computer and use it in GitHub Desktop.
Find peaks in a vector
#' Find peaks in a vector
#'
#' Which elements of a vector are greater than the value to their left and
#' right? First and last values need only be greater than their adjacent value.
#'
#' @param x vector of values
#' @return boolean vector of peak positions
is_peak <- function(x) {
n <- length(x)
x_i_minus_1 <- c(-Inf, x[1:(n - 1)])
x_i_plus_1 <- c(x[2:n], -Inf)
(x > x_i_minus_1) & (x > x_i_plus_1)
}
x <- c(3, 2, 1, 2, 4, 0, 1)
peaks <- is_peak(x)
print(x[peaks])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment