2017-06-17 36 views

回答

1

由於您尚未提供您的數據樣本,因此我將使用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') 
+0

我已經改變了代碼/重複的例子,使其更類似於您自己的數據。我希望現在的答案/解釋更清晰 –

+0

我不知道,但我只是GOOGLE了它,我發現這個https://stackoverflow.com/questions/36110815/how-to-use-disthaversine-function和https://stackoverflow.com/questions/21496587/error-in-pointstomatrixp1-latitude-90 –

+0

閱讀'?geosphere :: distHaversine'的幫助文件 - 它說「值:與r相同單位的距離矢量默認是米)「 – SymbolixAU

相關問題