Distance analysis in R

In today’s post, we’ll show you how to use the gDistance function from the rgeos library to calculate the distance between objects in a vector layers. For our example, we will use the railway lines (download) and fire department locations (download) that we already know from previous posts. First we load both layers and display the loaded layers:

We will use the function gDistance to calculate the distance. The arguments of the function are the two previously loaded layers between which we analyse the distance:

The result is a single distance, which is the shortest distance between the layer objects:

To get the distance matrix between the layer objects, it is necessary to add an additional argument byid, as in the gIntersects function:

The result is a distance matrix between all layer objects:

Finally, we want to use the function gDistance to find, for example, the guard unit whose straight line is closest to one of the line segments. Let’s choose the line segment with osm_id = 294250370:

The selected segment has a large distance to all fire units:

Let’s calculate the distance from the selected line to each fire unit:

The calculated distances are:

The minimum distance is:

The line closest to the selected line is:

You can use the learned function for many different analyses where you need to know the distance between objects. Do you have any other idea on how to use it? Post in the comments.

Leave a Reply

Your email address will not be published.

Translate using Google Translate»
Social media & sharing icons powered by UltimatelySocial

Podoba Ci się nasza strona? Odwiedź nasz profil