如何找到两个不同数据框之间的最近距离

How to find the nearest distance between two different data frames

我正在尝试查找数据集 1 中的位置与数据集 2 的最近距离。两个数据集的大小不同。我研究过使用 Haversine 函数,但不确定之后需要做什么。

由于您没有提供数据样本,我将使用 UScensus2000tract 库中的 oregon.tract 数据集作为可重现的示例。

这是我从 .

获得的基于快速 data.table 的解决方案
# load libraries
  library(data.table)
  library(geosphere)
  library(UScensus2000tract)
  library(rgeos)

现在让我们创建一个新的 data.table,其中包含起点(人口普查质心)和目的地(设施)的所有可能对组合

# get all combinations of origin and destination pairs
# Note that I'm considering here that the distance from A -> B is equal 
from B -> A.
  odmatrix <- CJ(Datatwo$Code_A , Dataone$Code_B)
  names(odmatrix) <- c('Code_A', 'Code_B') # update names of columns

# add coordinates of Datatwo centroids (origin)
  odmatrix[Datatwo, c('lat_orig', 'long_orig') := list(i.Latitude, 
i.Longitude), on= "Code_A" ]

# add coordinates of facilities (destination)
  odmatrix[Dataone, c('lat_dest', 'long_dest') := list(i.Latitude,  
i.Longitude), on= "Code_B" ]


Now you just need to:

# calculate distances
  odmatrix[ , dist := distHaversine(matrix(c(long_orig, lat_orig), ncol 
= 2), 
                                    matrix(c(long_dest, lat_dest), ncol  
= 2))]

# and get the nearest destinations for each origin
  odmatrix[, .(  Code_B = Code_B[which.min(dist)],
                    dist = min(dist)), 
                                    by = Code_A]

### Prepare data for this reproducible example
# load data
  data("oregon.tract")

# get centroids as a data.frame
  centroids <- as.data.frame(gCentroid(oregon.tract,byid=TRUE))

# Convert row names into first column
  setDT(centroids, keep.rownames = TRUE)[]

# get two data.frames equivalent to your census and facility data 
frames
  Datatwo<- copy(centroids)
  Dataone <- copy(centroids)

  names(Datatwo) <- c('Code_A', 'Longitude', 'Latitude')
  names(Dataone) <- c('Code_B', 'Longitude', 'Latitude')