正如您可能已经注意到的那样,distHaversine()
将计算单个点和两列坐标矩阵之间的距离。
计算之间的所有成对距离two坐标矩阵,只需使用apply()
逐行迭代一个矩阵,计算每个点到另一个矩阵中所有点的距离。
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
有趣的注释:快速浏览一下sp::spDists()
(which does计算两个矩阵之间的成对距离)表明它使用本质上相同的apply()
基于的策略。除了一些额外的错误检查和参数传递之外,主要区别在于它应用了函数spDistsN1()
我们在哪里申请distHaversine()
.