% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/kNNdist.R
\name{kNNdist}
\alias{kNNdist}
\alias{kNNdistplot}
\title{Calculate and Plot k-Nearest Neighbor Distances}
\usage{
kNNdist(x, k, all = FALSE, ...)

kNNdistplot(x, k, minPts, ...)
}
\arguments{
\item{x}{the data set as a matrix of points (Euclidean distance is used) or
a precalculated \link{dist} object.}

\item{k}{number of nearest neighbors used for the distance calculation.}

\item{all}{should a matrix with the distances to all k nearest neighbors be
returned?}

\item{...}{further arguments (e.g., kd-tree related parameters) are passed
on to \code{\link[=kNN]{kNN()}}.}

\item{minPts}{to use a k-NN plot to determine a suitable \code{eps} value for \code{\link[=dbscan]{dbscan()}},
\code{minPts} used in dbscan can be specified and will set \code{k = minPts - 1}.}
}
\value{
\code{kNNdist()} returns a numeric vector with the distance to its k
nearest neighbor. If \code{all = TRUE} then a matrix with k columns
containing the distances to all 1st, 2nd, ..., kth nearest neighbors is
returned instead.
}
\description{
Fast calculation of the k-nearest neighbor distances for a dataset
represented as a matrix of points. The kNN distance is defined as the
distance from a point to its k nearest neighbor. The kNN distance plot
displays the kNN distance of all points sorted from smallest to largest. The
plot can be used to help find suitable parameter values for \code{dbscan()}.
}
\examples{
data(iris)
iris <- as.matrix(iris[, 1:4])

## Find the 4-NN distance for each observation (see ?kNN
## for different search strategies)
kNNdist(iris, k = 4)

## Get a matrix with distances to the 1st, 2nd, ..., 4th NN.
kNNdist(iris, k = 4, all = TRUE)

## Produce a k-NN distance plot to determine a suitable eps for
## DBSCAN with MinPts = 5. Use k = 4 (= MinPts -1).
## The knee is visible around a distance of .7
kNNdistplot(iris, k = 4)

cl <- dbscan(iris, eps = .7, minPts = 5)
pairs(iris, col = cl$cluster + 1L)
## Note: black points are noise points
}
\seealso{
Other Outlier Detection Functions: 
\code{\link{glosh}()},
\code{\link{lof}()},
\code{\link{pointdensity}()}

Other NN functions: 
\code{\link{NN}},
\code{\link{comps}()},
\code{\link{frNN}()},
\code{\link{kNN}()},
\code{\link{sNN}()}
}
\author{
Michael Hahsler
}
\concept{NN functions}
\concept{Outlier Detection Functions}
\keyword{model}
\keyword{plot}
