[R] Nearest Neighbors

David L Carlson dcarlson at tamu.edu
Wed Jul 25 04:29:58 CEST 2012


Look at function get.knn in package FNN:

> library(FNN)
> set.seed(42)
> x <- rnorm(100, 50, 15)
> y <- rnorm(100, 50, 15)
> dat <- data.frame(x, y)
> knns <- get.knn(dat, k=4)
> str(knns)
> knns.ndx <- data.frame(knns[["nn.index"]])
> head(knns.ndx)

knns is a list with two components, a matrix of indices to the nearest
neighbors and a matrix of distances to the nearest neighbors.

----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of olemissrebs1123
> Sent: Tuesday, July 24, 2012 1:27 PM
> To: r-help at r-project.org
> Subject: Re: [R] Nearest Neighbors
> 
> I don't see the "obvious" portion. What I am looking for is an output
> that
> gives me an n*k matrix n (x,y) pairs k neighbors but using order say 4.
> 
> 
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/Nearest-
> Neighbors-tp4637618p4637648.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list