R/nnear.R

#' finds the nearest values in a vector to a specified target value
#'
#' \code{nnear(vect, target, n=1)}
#'
#' @param vect vector of numerical values
#' @param target target value which you want the nearest values to
#' @param n the n nearest values to return
#'
#' @return \code{index} position of the nearest n values within the original vector
#' @return \code{values} actual values of the nearest n values
#' @return \code{distance} absolute distance between the returned values and the target
#'
#' @details a simple utility for finding the nearest values in a vector to a specified
#' target value. The values, their position in the vector and the distance between each
#' and the target are returned as a list.


nnear = function(vect, target, n=1){
  vect[is.na(vect)]=Inf
  Diffs = vect[!is.na(vect)] - target
  AbDiffs = abs(Diffs)
  M = cbind(1:length(vect),vect,Diffs,AbDiffs)
  M = M[order(M[,4]),]
  return(list(index=M[1:n,1],values=M[1:n,2],distance=M[1:n,3]))
}
helophilus/ColsTools documentation built on May 30, 2019, 4:03 p.m.