Learn R Programming

SearchTrees (version 0.5.5)

knnLookup: Perform k-Nearest Neighbors Lookup Using a Search Tree

Description

This function performs fast k-Nearest Neighbors lookup on a SearchTree object

Usage

knnLookup(tree, newx, newy, newdat, columns = 1:2, k = 5)

Value

The return value is an integer matrix indicating the indices in the original data used to create treE where the nearest neighbors were found. Row indicates the indice of the new point, while column indicates the order of the k neighbors.

Arguments

tree

An object which inherits from the SearchTree S4 class.

newx

Numeric. Vector of x values for the points to look up neighbors for.

newy

Numeric. Vector of x values for the points to look up neighbors for.

newdat

Matrix or data.frame. Data containing x and y values of the points to look up neighbors for. Ignored if x and y are specified.

columns

Numeric. Columns x and y values can be found in within newdat.

k

Numeric. Number of neighbors to find for each point.

Author

Gabriel Becker

See Also

createTree rectLookup

Examples

Run this code
x = rnorm(100)
y = rnorm(100)
tree = createTree(cbind(x,y))
newx = c(0, .5)
newy = c(.5, 0)
inds = knnLookup(tree, newx, newy, k=7)

ch = rep(1, times=100)
ch[inds[1:7]] = 3
ch[inds[8:14]] = 5
cls = rep("black", times=100)
cls[inds[1:7]] = "red"
cls[inds[8:14]] ="blue"

plot(x,y, pch=ch, col = cls)
abline(v=newx[1], h = newy[1] , col="red")
abline(v=newx[2], h = newy[2], col = "blue")

Run the code above in your browser using DataLab