R/help_nearestNeighbourInt.R

#' Nearest neighbour interpolation.
#'
#' Nearest neighbour interpolation
#'
#' @param dat numeric vector
#'
#' @return
#'
#' @examples
#' library(zoo)
#' library(chron)
#' # load eddy covariance data
#' data(eses1)
#' # extract precipitation
#' P <- eses1$Precip
#' # nearest neighbor interpolation
#' P_interpol <- help_nearestNeighbourInt(P)
#'
#' @author Johannes Brenner \email{johannes.brenner@ufz.de}
#'
#' @references \url{http://stackoverflow.com/questions/10077415/replacing-nas-in-r-with-nearest-value}
#'
#' @seealso
#'
#' @keywords
#'
#' @export help_nearestNeighbourInt
#'

help_nearestNeighbourInt <- function(dat) {
  N <- length(dat)
  na.pos <- which(is.na(dat))
  if (length(na.pos) %in% c(0, N)) {
    return(dat)
  }
  non.na.pos <- which(!is.na(dat))
  intervals  <- findInterval(na.pos, non.na.pos,
                             all.inside = TRUE)
  left.pos   <- non.na.pos[pmax(1, intervals)]
  right.pos  <- non.na.pos[pmin(N, intervals+1)]
  left.dist  <- na.pos - left.pos
  right.dist <- right.pos - na.pos

  dat[na.pos] <- ifelse(left.dist <= right.dist,
                        dat[left.pos], dat[right.pos])
  return(dat)
}
JBrenn/Helper4me documentation built on May 7, 2019, 6:49 a.m.