# [R] Nearest Neighbors

David L Carlson dcarlson at tamu.edu
Mon Jul 30 00:45:40 CEST 2012

```Actually if you are looking for neighbors of neighbors you only need the
nearest neighbor for each point. The problem is that the nearest neighbor of
the nearest neighbor of point 1 is often point 1. Did you want the nearest
neighbor not counting any point twice? Sounds more like a traveling salesman
problem or nearest link cluster analysis.

> set.seed(42)
> x <- rnorm(100, 50, 15)
> y <- rnorm(100, 50, 15)
> dat <- cbind(x, y)
> library(spdep)
> nn <- knearneigh(dat, 1)
> nn1 <- nn\$nn # Nearest neighbors
> nn2 <- nn1[nn1] # Nearest neighbor of the nearest neighbor
> nn3 <- nn2[nn1] # Third order
> nn4 <- nn3[nn1] # Fourth order
> head(cbind(nn1, nn2, nn3, nn4), 10)
nn2 nn3 nn4
[1,] 53   1  53   1
[2,] 34   2  34   2
[3,] 67   3  67   3
[4,] 35  60  46  60
[5,] 82   5  82   5
[6,] 10   6  10   6
[7,] 48   7  48   7
[8,] 40   8  40   8
[9,] 25   9  25   9
[10,]  6  10   6  10

----------------------------------------------
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 Petr Savicky
> Sent: Sunday, July 29, 2012 1:44 PM
> To: r-help at r-project.org
> Subject: Re: [R] Nearest Neighbors
>
> On Tue, Jul 24, 2012 at 09:26:49AM -0700, olemissrebs1123 wrote:
> > I was wondering if there is a way in R to find k nearest neighbors of
> various
> > orders, say order 2, 3, or 4. In otherwords neighbors of neighbors of
> > neighbors. You get the idea. I know that I can use
> knearneigh(matrix.data,
> > k) but this only gives me the k nearest neighbors and not of a
> particular
> > order.
>
> Hi.
>
> If i understand correctly, then this may be achieved by several
> iterations.
> In the first iteration, the nearest neighbours are found. The next
> iteration
> starts from them a finds their nearest neighbours. These are neighbours
> of
> order 2. A general iteration finds neighbours of order n by looking for
> neighbours
> of the points found in the previous step, which are the neighours of
> order n-1.
>
> Hope this helps.
>
> Petr Savicky.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> guide.html
> and provide commented, minimal, self-contained, reproducible code.

```