R/kernel_weights.R

Defines functions kernel_weights

Documented in kernel_weights

#' Compute kernel weights from distances
#'
#' @param distances Numeric vector of distances.
#' @param bandwidth Positive numeric bandwidth.
#' @param kernel Kernel type: "bisquare", "gaussian", or "tricube".
#'
#' @return A numeric vector with the same length as `distances`. Each element
#' is the spatial kernel weight assigned to the corresponding observation,
#' with larger weights generally assigned to observations closer to the focal
#' location.
#'
#' @examples
#' distances <- c(0, 1, 2, 3)
#'
#' kernel_weights(
#'   distances = distances,
#'   bandwidth = 3,
#'   kernel = "bisquare"
#' )
#' @export
kernel_weights <- function(distances, bandwidth, kernel = "bisquare") {
  if (!is.numeric(distances)) {
    stop("distances must be numeric.")
  }
  if (!is.numeric(bandwidth) || length(bandwidth) != 1 || is.na(bandwidth) || bandwidth <= 0) {
    stop("bandwidth must be one positive numeric value.")
  }
  if (!kernel %in% c("bisquare", "gaussian", "tricube")) {
    stop("kernel must be one of: 'bisquare', 'gaussian', 'tricube'.")
  }

  u <- distances / bandwidth

  w <- switch(
    kernel,
    bisquare = ifelse(u < 1, (1 - u^2)^2, 0),
    gaussian = exp(-0.5 * u^2),
    tricube  = ifelse(u < 1, (1 - abs(u)^3)^3, 0)
  )

  w[!is.finite(w)] <- 0
  as.numeric(w)
}

Try the gwrf package in your browser

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

gwrf documentation built on Aug. 24, 2026, 5:15 p.m.