0

I have two data frames. One has ~600 or so locations of people on a map, like so:

Names<-c("Mike","Ron","Joe")
Lat<-c(61.5,63.2,50.1)
Long<-c(-140.2,-139.2,-145.6)
df<-data.frame(Names,Lat,Long)

The other has locations those people might need to get to:

Places<-c("ClinicA","ClinicB","ClinicC")
Lat<-c(58.5,50.2,40.1)
Long<-c(-135.2,-133.2,-140.6)
df1<-data.frame(Places,Lat,Long)

I know that if I have an individual set of coordinates I can use googleway to get the distances in between like so:

df <- google_distance(origins = list(c("Melbourne Airport, Australia"),
                                 c("MCG, Melbourne, Australia"),
                                 c(-37.81659, 144.9841)),
                  destinations = c("Portsea, Melbourne, Australia"),
                  key = key)

My question is, I'd like to go through each individual person, calculate the distance to each of the locations of the places (i.e. return three different distances for each person), and then only keep the smallest distance for each. The resulting data frame would hopefully be:

Rows of: Name, lat,long,NearestPlace,Distance to that place

I'm assuming it'd maybe be a "for" loop, but I'm kinda lost at this point. Any help would be appreciated, thank you!

Joe Crozier
  • 944
  • 8
  • 20
  • 1
    Are the Lat and Long values in `df` and `df1` legit? – JasonAizkalns Sep 13 '18 at 16:28
  • Oh I just made those particular ones up (you're referring to the -135.2, -133.2?) but they SHOULD work, even without the extra decimal places. Is that what you meant? Oh, I guess 58 is too high. But besides that, if you took like 30,-145 – Joe Crozier Sep 13 '18 at 16:30
  • I don't believe the distance API works correctly with just random collections of Lat/Long – JasonAizkalns Sep 13 '18 at 17:10
  • Yea I just saw that when I tried those numbers (wouldn't give me a distance if the location was in the middle of the ocean). That being said, assuming we had real, on-land, locations (which we do), do you have any ideas of how I could write that code? Thank you! – Joe Crozier Sep 13 '18 at 17:15
  • 2
    Looks like this has already been [answered](https://stackoverflow.com/q/48929667/2572423). – JasonAizkalns Sep 13 '18 at 18:06
  • 2
    If you're only after the shortest distance (as the crow flies) there are much simpler methods for solving this which won't require loops or calls to Google's API. Otherwise, if you actually need the driving/walking/route distances then the answer linked by @JasonAizkalns might be what you're after – SymbolixAU Sep 13 '18 at 22:06
  • Actually SymbolixAU, that would definitely help! The google API thing looks like it would take 100,000 searches, which at that volume I'd have to pay for. Unfortunately I'm kinda lost as to which other methods I could use. Could you point me in the right direction? – Joe Crozier Sep 17 '18 at 13:12

0 Answers0