0
我正在嘗試查找數據集1中數據集2中位置的最近距離。兩個數據集都是不同的大小。我研究過使用Haversine函數,但我不確定我需要做什麼。如何找到兩個不同數據幀之間的最近距離
我正在嘗試查找數據集1中數據集2中位置的最近距離。兩個數據集都是不同的大小。我研究過使用Haversine函數,但我不確定我需要做什麼。如何找到兩個不同數據幀之間的最近距離
由於您尚未提供您的數據樣本,因此我將使用UScensus2000tract
庫中的oregon.tract
數據集作爲可重現的示例。
這是一個基於快速data.table
的解決方案,我從this other answer here獲得。
# 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')
我已經改變了代碼/重複的例子,使其更類似於您自己的數據。我希望現在的答案/解釋更清晰 –
我不知道,但我只是GOOGLE了它,我發現這個https://stackoverflow.com/questions/36110815/how-to-use-disthaversine-function和https://stackoverflow.com/questions/21496587/error-in-pointstomatrixp1-latitude-90 –
閱讀'?geosphere :: distHaversine'的幫助文件 - 它說「值:與r相同單位的距離矢量默認是米)「 – SymbolixAU