Search code examples
rgisgeospatialgeosphere

How to use longitude and latitude data effectively with distHarvesine()?


This is mostly a follow-up question on an older post (2017) see old post here

I have been working on a similar project and I appreciate the 2017 post for its usefulness. However, I struggle to understand and cannot find any documentation or information on what do the arguments longitude[-n()] and longitude[ -1] mean in the following context where someone calculates the distance between two geolocations.

distance = c(NA,
          distHaversine(cbind(longitude[-n()], latitude[-n()]),
                        cbind(longitude[  -1], latitude[  -1])))

I'm honestly new with geospatial analysis in R and I would really appreciate any lead on this.

Thanks in advance.


Solution

  • This statement: cbind(longitude[-n()], latitude[-n()] removes the last element from the vector, while this cbind(longitude[ -1], latitude[ -1]) removes the first first element of the vector.

    distHaversine also has a simpler syntax where if you just pass a single data.frame it will calculate the distances between the elements. For example:

    distHaversine(cbind(longitude, latitude)