2017-06-17 82 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

相关问题