With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

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: (x2x1)2 + (y2y1)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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required