I have two dataframes. 'Origins' contains X pairs of longitude/latitude coordinates, and 'Destinations' contains five pairs of coordinates for locations of interest. For each lon/lat pair in Origins, I want to compute the distances to each of the five lon/lat pairs in Destinations. Note that the five locations of interest in Destinations are the same at every iteration of Origins. This is trivial with a loop but I have X=500,000 Origins coordinates to process for each of the five Destinations coordinates and something faster is needed. For this example, we'll say Origins has two rows.
Origins <-
data.frame(Lon1 = c(-100, -50),
Lat1 = c(20, 10))
Destinations <-
data.frame(Lon2 = c(-91, -151, -139, -140, -100),
Lat2 = c(9, 10, 11, 8, 5))
The result I want should have N=2 rows, one for each row of Origins, and N=5 columns containing the computed distances from the Origin in that row to each of the five Destinations.
geosphere::distRhumb() calculates the distance between two points (pairs of lon/lat coordinates), p1 and p2.
Using apply() by row of Origins seems like the way forward but I'm failing badly at specifying the syntax. Most of the time I just get errors. The following configuration at least executes but just returns the distance between the two coordinates listed in Origins:
apply(Origins, 1, function(Destinations){
geosphere::distRhumb(p1 = Origins, p2 = Destinations)})
Any help is gratefully appreciated.
Use the function below: