首页 > 解决方案 > Geosphere 的距离矩阵:避免重复计算

问题描述

我想使用 from 计算一个非常大的矩阵中所有点之间的distm距离geosphere

看一个最小的例子:

library(geosphere)
library(data.table)

coords <- data.table(coordX=c(1,2,5,9), coordY=c(2,2,0,1))
distances <- distm(coords, coords, fun = distGeo)

问题是,由于我正在计算的距离的性质,distm给了我一个对称矩阵,因此,我可以避免计算超过一半的距离:

structure(c(0, 111252.129800202, 497091.059564718, 897081.91986428, 
111252.129800202, 0, 400487.621661164, 786770.053508848, 497091.059564718, 
400487.621661164, 0, 458780.072878927, 897081.91986428, 786770.053508848, 
458780.072878927, 0), .Dim = c(4L, 4L))

你能帮我找到一种更有效的方法来计算所有这些距离,避免每次做两次吗?

标签: rdistancegeosphere

解决方案


如果要计算点的所有成对距离x,最好使用distm(x)而不是distm(x,x). 该distm函数在两种情况下都返回相同的对称矩阵,但是当您向其传递单个参数时,它知道该矩阵是对称的,因此它不会进行不必要的计算。

你可以计时。

library("geosphere")

n <- 500
xy <- matrix(runif(n*2, -90, 90), n, 2)

system.time( replicate(100, distm(xy, xy) ) )
#  user  system elapsed 
# 61.44    0.23   62.79 
system.time( replicate(100, distm(xy) ) )
#  user  system elapsed 
# 36.27    0.39   38.05 

您还可以查看 R 代码geosphere::distm以检查它是否以不同的方式处理这两种情况。

旁白:快速谷歌搜索发现parallelDist:CRAN 上的并行距离矩阵计算。测地线距离是一种选择。


推荐阅读