本文介绍了如何找到两个不同数据框之间的最近距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到数据集1到数据集2的最近距离.这两个数据集的大小不同.我已经研究过使用Haversine函数,但是我不确定之后需要做什么.
I am trying to find the nearest distance of locations in dataset 1 to dataset 2. Both data sets are different sizes. Ive looked into using the Haversine function but I'm unsure what I need to do after.
推荐答案
由于您没有提供数据样本,因此我将使用UScensus2000tract
库中的oregon.tract
数据集作为可重复的示例.
Since you have not provided a sample of your data, I am going to use the oregon.tract
data set from the UScensus2000tract
library as a reproducible example.
这是我从.
# load libraries
library(data.table)
library(geosphere)
library(UScensus2000tract)
library(rgeos)
现在,让我们创建一个新的data.table
,其中包含起点(普查质心)和终点(便利设施)的所有可能的配对组合
Now let's create a new data.table
with all possible pair combinations of origins (census centroids) and destinations (facilities)
# 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')
这篇关于如何找到两个不同数据框之间的最近距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!