% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/knn.R
\name{knn}
\alias{knn}
\title{Spatial K nearest neighbor}
\usage{
knn(
  y,
  x,
  k = 1,
  d = NULL,
  ids = NULL,
  weights.y = NULL,
  weights.x = NULL,
  indexes = FALSE
)
}
\arguments{
\item{y}{Spatial sf object or coordinates matrix}

\item{x}{Spatial points or polygons object or coordinates matrix}

\item{k}{Number of neighbors}

\item{d}{Optional search radius}

\item{ids}{Optional column of ID's in x}

\item{weights.y}{A vector or matrix representing covariates of y}

\item{weights.x}{A vector or matrix representing covariates of x}

\item{indexes}{(FALSE/TRUE) Return row indexes of x neighbors}
}
\value{
A data.frame with row indexes (optional), rownames, ids (optional) and 
distance of k
}
\description{
Find K nearest neighbors for two spatial objects
}
\details{
Finds nearest neighbor in x based on y and returns rownames, index and distance,
If ids is NULL, rownames of x are returned. If coordinate matrix provided, 
columns need to be ordered [X,Y]. If a radius for d is specified than a maximum 
search radius is imposed. If no neighbor is found, a neighbor is not returned  

You can specify weights to act as covariates for x and y. The vectors or matrices
must match row dimensions with x and y as well as columns matching between weights.
In other words, the covariates must match and be numeric.
}
\examples{
\donttest{
if(require(sp, quietly = TRUE)) {
library(sf)
  data(meuse, package = "sp")
  meuse <- st_as_sf(meuse, coords = c("x", "y"), crs = 28992, 
                    agr = "constant")
 
# create reference and target obs
idx <- sample(1:nrow(meuse), 10) 
  pts <- meuse[idx,]
    meuse <- meuse[-idx,]
    meuse$IDS <- 1:nrow(meuse)
 
# Find 2 neighbors in meuse
( nn <- knn(pts, meuse, k=2, ids = "IDS", indexes = TRUE) )
  plot( st_geometry(pts), pch=19, main="KNN")
    plot(st_geometry(meuse[nn[,1],]), pch=19, col="red", add=TRUE)

# Using covariates (weights)
wx = as.matrix(st_drop_geometry(meuse[,1:3]))
wy = as.matrix(st_drop_geometry(pts[,1:3]))

( nn <- knn(pts, meuse, k=2, ids = "IDS", indexes = TRUE,
            weights.y=wy, weights.x=wx) )
  plot(st_geometry(pts), pch=19, main="KNN")
    plot(st_geometry(meuse[nn[,1],]), pch=19, col="red")
	  
# Using coordinate matrices
y <- st_coordinates(pts)[,1:2]
x <- st_coordinates(meuse)[,1:2]
knn(y, x, k=2)

} else { 
  cat("Please install sp package to run example", "\n")
}
}
  
}
\seealso{
\code{\link[RANN]{nn2}} for details on search algorithm
}
\author{
Jeffrey S. Evans  <sage_insights@outlook.com>
}
