Learn R Programming

SearchTrees (version 0.1.6)

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

Description

This function performs fast Nearest Neighbors lookup on an object created using createIndex

Usage

findKNN(tree, newdat, fulldat, newcols = 1:2, fullcols = 1:2, k = 5)

Arguments

tree
An object which inherits from the SearchTree S4 class.
newdat
A matrix or data.frame containing the data for the points to lookup neighbors for.
fulldat
A matrix or data.frame containing the data used to create tree
newcols
The columns within newdat where the relevant data can be found. Defaults to columns 1 and 2.
fullcols
The columns within fulldat where the relevant data can be found. Defaults to columns 1 and 2.
k
Number of Nearest Neighbors to find for each new point in newdat

Value

  • The return value is an integer matrix indicating the indices in fulldat where the nearest neighbors were found. Row indicates point in newdat, while column indicates the order of the k neighbors.

See Also

createIndex, getPointsInRect

Examples

Run this code
x= rnorm(100)
y = rnorm(100)
dat = cbind(x,y)
newdat = cbind(rnorm(2), rnorm(2))
tree = createIndex(dat)
inds = findKNN(tree, newdat, dat)

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

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

Run the code above in your browser using DataLab