2

dist(coords) provides the distance matrix using Euclidean distances; it also provides several other options. But it doesn't provide any option such as the haversine formula.

distHaversine() calculates the distance I want (great-circle) for given two set of lat/long coordinates. I am wondering if there is an existing package/function that calculates great-circle distance matrix using the haversine formulation.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
cmelan
  • 247
  • 5
  • 13

1 Answers1

6

As you may already have noticed, distHaversine() will compute the distance between a single point and a two-column matrix of coordinates.

To compute all pairwise distances between two coordinate matrices, just use apply() to iterate row-by-row through one of the matrices, computing each of its points' distance to all of the points in the other.

library(geosphere)

## Example coordinates (here stored in two column matrices)
cc1 <- rbind(c(0,0),c(1,1))
cc2 <- rbind(c(90,0),c(90,90), c(45,45))

## Compute matrix of distances between points in two sets of coordinates
apply(cc1, 1, FUN=function(X) distHaversine(X, cc2))
#          [,1]    [,2]
# [1,] 10018754 9907452
# [2,] 10018754 9907435
# [3,]  6679169 6524042

Interesting note: A quick glance under the hood at sp::spDists() (which does compute pairwise distances between two matrices) reveals that it uses an essentially identical apply()-based strategy. The main difference, beyond some additional error checking and argument passing is that it applies the function spDistsN1() where we apply distHaversine().

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • 1
    Perfect! `spDists(data, longlat=TRUE)` is exactly what I am looking for. Thanks! – cmelan May 12 '14 at 17:57
  • 1
    Great. Just for the record, it doesn't immediately seem that `spDists()`' uses the Haversine formula for its "Great Circle distance (WGS84 ellipsoid)" distance computations. You'll know, though, whether that matters for your application. – Josh O'Brien May 12 '14 at 18:14