How to get the second nearest neighbor between two point patterns in R?

The function get.knnx in package FNN can compute the N-nearest neighbours in point patterns.

x1 = cbind(runif(10),runif(10))
x2 = cbind(runif(10),runif(10))
nn = get.knnx(x1,x2,2)

now nn$nn.index is a matrix such that nn$nn.index[i,j] is the row in x1 of the two nearest neighbours to row i in x2 - sorted so that the nearest is [i,1], and the next neighbour is [i,2].

The function also returns the distances for you, and has some options to compute spatial indexes for very fast searches.


I just discovered that spatstat has a crossdist function.

Description

Computes the distances between pairs of ‘things’ taken from two different datasets.

It takes two point patterns X and Y as inputs, and returns the matrix whose [i,j] entry is the distance from X[i] to Y[j]. To get the second nearest neighbors using crossdist:

xdistances <- crossdist(X, Y)  #Get all cross distances    

nn = numeric() 
for (i in 1:nrow(X)) {   
  xdistance <- sort(xdistances[i,], partial=2)[2]   
  nn <- append(nn, xdistance)
}

I know I already accepted Spacedman's answer but I would like to share how I did it in another way.

Tags:

R

Spatstat