2017-06-17 3 views

Antwort

1

Da Sie keine Probe Ihrer Daten bereitgestellt haben, werde ich den oregon.tract Datensatz aus der UScensus2000tract Bibliothek als ein reproduzierbares Beispiel verwenden.

Hier ist eine Lösung basierend auf schnelle data.table, die ich von this other answer here bekomme.

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

Lassen Sie uns jetzt einen neuen data.table mit allen möglichen Paarkombinationen von Herkunft (Volkszählung Zentroide) erstellen und Ziele (Einrichtungen)

# 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

Ich habe den Code/reproduzierbaren Beispiel geändert, um es zu ähnlicher machen Ihre eigene Daten. Ich hoffe, die Antwort/Erklärung ist jetzt klarer –

+0

Ich weiß es nicht, aber ich googelte es und ich habe diese https://stackoverflow.com/questions/36110815/how-to-use-disthaversine-function Und gefunden https://StackOverflow.com/Questions/21496587/error-in-pointstomatrixP1-Latitude-90 –

+0

lesen Sie die Hilfedatei für '? Geosphere :: DistHaversine' - es sagt" Wert: Vektor der Entfernungen in der gleichen Einheit wie R (Standard ist Meter) " – SymbolixAU

Verwandte Themen