r - 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))
你能帮我找到一种更有效的方法来计算所有这些距离,避免每次做两次吗?
解决方案
如果要计算点的所有成对距离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 上的并行距离矩阵计算。测地线距离是一种选择。
推荐阅读
- .htaccess - 我可以为在域内单击的链接禁用热链接保护吗
- validation - 长 GateKeeper 应用程序验证的进度条
- c# - C# 不强制类实现公共接口
- javascript - 多个组件的 useEffect、useState 和 useContext 的 React Hooks 生命周期是什么?
- angular - 我应该如何将 datetime json 字符串属性映射到 TypeScript 日期类型?
- oracle - “CLOB”列上的行锁争用
- python - sum([.25,.35,.3,.1,0]) 给出 0.999999(9) 而不是 1。为什么?
- scala - for后如何避免平面图
- c - 输入的数字字符
- python - 无法安装 nlopt python 模块