从一个数据集到第二个数据集查找最近的点(纬度/经度)

mbf*_*mbf 5 r distance spatial latitude-longitude geosphere

我有两个数据集 A 和 B,它们给出了英国不同点的位置,如下所示:

A = data.frame(reference = c(C, D, E), latitude = c(55.32043, 55.59062, 55.60859), longitude = c(-2.3954998, -2.0650243, -2.0650542))

B = data.frame(reference = c(C, D, E), latitude = c(55.15858, 55.60859, 55.59062), longitude = c(-2.4252843, -2.0650542, -2.0650243))
Run Code Online (Sandbox Code Playgroud)

A 有 400 行,B 有 1800 行。
对于 A 中的所有行,我想找到 A 中的一个点与 B 中三个最近点中的每一个之间的最短距离(以公里为单位),以及 B 中这些点的经纬度参考和坐标。

我尝试使用这篇文章

R - 在给定半径内找到最近的相邻点和相邻点的数量,坐标经纬度

但是,即使我按照所有说明进行操作,主要是使用distmpackage 中的命令geosphere,距离也会以不可能为公里的单位出现。我看不到代码中要更改的内容,尤其是因为我对这些geo包根本不熟悉。

Dav*_*e2e 1

这是使用单个循环并将距离计算矢量化(转换为公里)的解决方案。
该代码使用基本 Rrank函数对计算距离列表进行排序/排序。
索引和计算出的 3 个最短值的距离存储回数据帧 A 中。

library(geosphere)

A = data.frame(longitude = c(-2.3954998, -2.0650243, -2.0650542), latitude = c(55.32043, 55.59062, 55.60859))
B = data.frame(longitude = c(-2.4252843, -2.0650542, -2.0650243), latitude = c(55.15858, 55.60859, 55.59062))

for(i in 1:nrow(A)){
  #calucate distance against all of B
  distances<-geosphere::distGeo(A[i,], B)/1000
  #rank the calculated distances
  ranking<-rank(distances, ties.method = "first")

  #find the 3 shortest and store the indexes of B back in A
  A$shortest[i]<-which(ranking ==1) #Same as which.min()
  A$shorter[i]<-which(ranking==2)
  A$short[i]<-which(ranking ==3)

  #store the distances back in A
  A$shortestD[i]<-distances[A$shortest[i]] #Same as min()
  A$shorterD[i]<-distances[A$shorter[i]]
  A$shortD[i]<-distances[A$short[i]]
}
A

  longitude latitude shortest shorter short shortestD  shorterD   shortD
1 -2.395500 55.32043        1       3     2  18.11777 36.633310 38.28952
2 -2.065024 55.59062        3       2     1   0.00000  2.000682 53.24607
3 -2.065054 55.60859        2       3     1   0.00000  2.000682 55.05710
Run Code Online (Sandbox Code Playgroud)

正如 M Viking 指出的,对于地圈包,数据必须按经纬度排列。