Nearest Neighbours
Suppose that we have been set the problem of drawing lines to join the nearest neighbour pairs of any given set of points (x, y) that are mapped in two dimensions. There are three steps to the computing: we need to
- compute the distance to every neighbour;
- identify the smallest neighbour distance for each individual;
- use these minimal distances to identify all the nearest neighbours.
We start by generating a random spatial distribution of 100 individuals by simulating their x and y coordinates from a uniform probability distribution:
x<-runif(100) y<-runif(100)
The graphics parameter pty="s" makes the plotting area square, as we would want for a map like this:
par(pty="s") plot(x,y,pch=16)

Computing the distances is straightforward: for each individual we use Pythagoras to calculate the distance to every other plant. The distance between two points with coordinates (x1, y1) and (x2, y2) is d:

The square on the hypotenuse (d2) is the sum of the squares on the two adjacent sides: (x2 – x1)2 + (y2 – y1)2 so the distance d is given by
![]()
We write a function for this as follows:
distance<-function(x1, y1, x2, y2) sqrt((x2 – x1)^2 + (y2 – y1)^2)
Now we loop through ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access