#' 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)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.