![](/img/trans.png)
[英]R code to calculate distance between multiple latitude-longitude pairs and extract the closest pairs
[英]Trying to find the distance between pairs of latitude and longitude coordinates
目前有一個 4 列的數據框,“lon.x”、“lat.x”、“lon.y”、“lat.y”。 有 581 行。 我想找到每對坐標之間的距離。
我試過了:
library(geosphere)
distm(c(coords$lon_x, coords$lat_x),c(coords$lon_y, coords$lat_y), fun = distHaversine())
但是得到了這個錯誤
Error in .pointsToMatrix(x) : Wrong length for a vector, should be 2
有不同的方法可以做到這一點嗎?
使用distm(cbind(coords$lon_x, coords$lat_x), cbind(coords$lon_y, coords$lat_y), distHaversine)
或distm(coords[, c("lon_x", "lat_x")], coords[, c("lon_y", "lat_y")], distHaversine)
對我有用,或者更簡潔地使用with
:
library(geosphere)
res <- with(coords, distm(cbind(lon_x, lat_x), cbind(lon_y, lat_y), distHaversine))
res
# [,1] [,2] [,3] [,4] [,5]
# [1,] 82926.65 102777.0 416520.9 317338.5 229201.72
# [2,] 227148.47 371663.8 472784.4 441059.9 51871.09
# [3,] 131700.50 212885.3 344615.2 270580.8 166672.80
# [4,] 170629.69 314137.0 566038.0 506409.5 114399.77
# [5,] 125941.89 208759.0 350108.9 275223.3 164881.02
不過,您只需要diag
。
diag(res)
# [1] 82926.65 371663.76 344615.24 506409.47 164881.02
查看:
with(coords, distm(cbind(lon_x, lat_x)[1,], cbind(lon_y, lat_y)[1,], distHaversine))
# [,1]
# [1,] 82926.65
with(coords, distm(cbind(lon_x, lat_x)[2,], cbind(lon_y, lat_y)[2,], distHaversine))
# [,1]
# [1,] 371663.8
with(coords, distm(cbind(lon_x, lat_x)[3,], cbind(lon_y, lat_y)[3,], distHaversine))
# [,1]
# [1,] 344615.2
玩具數據:
n <- 5
set.seed(42)
coords <- data.frame(id=seq(n),
lon_x=rnorm(n, 47.364842), lat_x=rnorm(n, 8.573026),
lon_y=rnorm(n, 47.364842), lat_y=rnorm(n, 8.573026),
sth_else=rnorm(n))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.