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()
.
library("sos"); findFn("{great circle} distance")
(and variations)? – Ben Bolker