Calculating great-circle distance matrix

送分小仙女□ 提交于 2019-12-02 12:52:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!