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 (*x*_{1}, *y*_{1}) and (*x*_{2}, *y*_{2}) is *d*:

The square on the hypotenuse (*d*^{2}) is the sum of the squares on the two adjacent sides: (*x*_{2} – *x*_{1})^{2} + (*y*_{2} – *y*_{1})^{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 ...

Start Free Trial

No credit card required