2017-06-17 7 views

答えて

1

データのサンプルを提供していないので、再現可能な例としてUScensus2000tractライブラリのoregon.tractデータセットを使用します。

ここでは、this other answer hereから得る高速data.tableに基づく解決策があります。

# load libraries 
    library(data.table) 
    library(geosphere) 
    library(UScensus2000tract) 
    library(rgeos) 

今、私はあなたにそれをより近づけるために、コード/再現性の例を変更したのは、すべての可能な起源のペアの組み合わせ(国勢調査の重心)と目的地(施設)

# 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

で新しいdata.tableを作成してみましょう自分のデータ。 –

+0

私は知らないが、私はそれを見つけただけで、これを見つけた。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

関連する問題