![](/img/trans.png)
[英]Using the geosphere distm function on a data.table to calculate distances
[英]Matrix of distances with Geosphere: avoid repeat calculus
我想使用來自地geosphere
distm
來計算非常大的矩陣中所有點之間的距離。
看一個最小的例子:
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))
你可以幫我找一個更有效的方法來計算所有這些距離,避免每次做兩次嗎?
您可以准備可能組合的數據框而無需重復(使用gtools
包)。 然后計算這些對的距離。 這是代碼:
library(gtools)
library(geosphere)
library(data.table)
coords <- data.table(coordX = c(1, 2, 5, 9), coordY = c(2, 2, 0, 1))
pairs <- combinations(n = nrow(coords), r = 2, repeats.allowed = F, v = c(1:nrow(coords)))
distances <- apply(pairs, 1, function(x) {
distm(coords[x[1], ], coords[x[2], ], fun = distGeo)
})
# Construct distances matrix
dist_mat <- matrix(NA, nrow = nrow(coords), ncol = nrow(coords))
dist_mat[upper.tri(dist_mat)] <- distances
dist_mat[lower.tri(dist_mat)] <- distances
dist_mat[is.na(dist_mat)] <- 0
print(dist_mat)
結果:
[,1] [,2] [,3] [,4]
[1,] 0.0 111252.1 497091.1 400487.6
[2,] 111252.1 0.0 897081.9 786770.1
[3,] 497091.1 400487.6 0.0 458780.1
[4,] 897081.9 786770.1 458780.1 0.0
如果要計算點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
您還可以查看geosphere::distm
的R代碼,以檢查它geosphere::distm
以不同方式處理這兩種情況。
除此之外:快速谷歌搜索找到parallelDist
:CRAN上的並行距離矩陣計算。 測地距離是一種選擇。
使用基礎R中的combn()
可能稍微簡單一些,並且可能比加載其他包更快。 然后, distm()
使用distGeo()
作為源,因此使用后者應該更快。
coords <- as.data.frame(coords) # this won't work with data.tables though
cbind(t(combn(1:4, 2)), unique(geosphere::distGeo(coords[combn(1:4, 2), ])))
# [,1] [,2] [,3]
# [1,] 1 2 111252.1
# [2,] 1 3 497091.1
# [3,] 1 4 897081.9
# [4,] 2 3 786770.1
# [5,] 2 4 400487.6
# [6,] 3 4 458780.1
我們可以用基准測試一下。
Unit: microseconds
expr min lq mean median uq max neval cld
distm 555.690 575.846 597.7672 582.352 596.1295 904.718 100 b
distGeo 426.335 434.372 450.0196 441.516 451.8490 609.524 100 a
看起來不錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.