R: Perform k-Nearest Neighbors Lookup Using a Search Tree
knnLookup
R Documentation
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)
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.
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.
Note
No defined order is specified for exact ties in distance.
Author(s)
Gabriel Becker
See Also
createTreerectLookup
Examples
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")
Results
R version 3.3.1 (2016-06-21) -- "Bug in Your Hair"
Copyright (C) 2016 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> library(SearchTrees)
> png(filename="/home/ddbj/snapshot/RGM3/R_CC/result/SearchTrees/knnLookup.Rd_%03d_medium.png", width=480, height=480)
> ### Name: knnLookup
> ### Title: Perform k-Nearest Neighbors Lookup Using a Search Tree
> ### Aliases: knnLookup 'knnLookup, QuadTree-method'
> ### Keywords: knn lookup neighbors
>
> ### ** Examples
>
> 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")
>
>
>
>
>
> dev.off()
null device
1
>