R/Rfun_interpolate_zero.R

Defines functions interpolate_zero

Documented in interpolate_zero

#' Calculate the x-coordinates of a function where zero crossings occur
#'
#' @param values a numeric vector representing the function's output at specific points
#' @param x Aa vector of x-coordinates corresponding to the values. If not provided, it defaults to 1:length(values)
#'
#' @returns the x-coordinates where zero crossings occur. If no crossings are found, it returns NA
#' @export
#'
interpolate_zero <- function(values, x = NULL) {
  # values: A numeric vector representing the function's output at specific points.
  # x: A vector of x-coordinates corresponding to the values. If not provided, it defaults to 1:length(values).
  # Output: Returns the x-coordinates where zero crossings occur. If no crossings are found, it returns NA
  #
  # Ensure the x vector is provided or create a default index
  if (is.null(x)) {
    x <- seq_along(values)
  }
  # Find indices where the sign of values changes
  zero_crossings <- which(diff(sign(values)) != 0)
  if (length(zero_crossings) == 0) {
    return(NA) # No zero crossings found
  }
  # Linear interpolation for each zero crossing
  interpolated_zeros <- sapply(zero_crossings, function(i) {
    # Values and x-coordinates for the crossing interval
    x1 <- x[i]
    x2 <- x[i + 1]
    y1 <- values[i]
    y2 <- values[i + 1]
    # Linear interpolation formula
    x_zero <- x1 - y1 * (x2 - x1) / (y2 - y1)
    return(x_zero)
  })
  return(interpolated_zeros)
}

Try the itrimhoch package in your browser

Any scripts or data that you put into this service are public.

itrimhoch documentation built on June 8, 2025, 11:54 a.m.