问题
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.
回答1:
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()
.
来源:https://stackoverflow.com/questions/23615063/calculating-great-circle-distance-matrix