Learn R Programming

smacpod (version 1.4.1)

nn: Determine nearest neighbors

Description

nn determines the nearest neighbors for a set of observations based on the distance matrix.

Usage

nn(d, k, method = "c", self = FALSE)

Arguments

d

A square distance matrix for the set of coordinates of interest.

k

The number of numbers to return (if method = "c") or the distance for which observations are considered neighbors (if method = "d").

method

The method of determining the neighbors. The default is "c", specifying that the k nearest neighbors (the count of neighbors) for each observation should be returned. The alternative is "d", meaning that neighbors are determined by their distance from an observation. In that case, two observations are neighbors if their separation distance is less or equal to k.

self

A logical indicating whether an observation is a neighbor with itself. The default is FALSE.

Value

Returns the indexes of the nearest neighbors as a matrix if method = "c" and a list otherwise. For each row or element of the list, the indexes are ordered from nearest to farthest.

Details

This function can determine nearest neighbors in two ways: 1. by total count or 2. by distance. If method = "c", then k determines the total number of neighbors to return for each observation. If method = "d", then k determines the distance for which an observation is considered a neighbor.

Examples

Run this code
# NOT RUN {
data(grave)
# make distance matrix
d = as.matrix(dist(cbind(grave$x, grave$y)))
# 3 nearest neighbors
nnc = nn(d, k = 3, method = "c")
# nearest neighbors within k units of each observation
nnd = nn(d, k = 200, method = "d")
# }

Run the code above in your browser using DataLab