Calculate distance between two points given lat and long

I’ve been trying to get pairwise distances between my sample point using the R geosphere package but I can’t seem to get a clear result with labels – as in, I have no idea what the points are.

Here is a sample of my data:

GridID  Longitude   Latitude
A13 -79.320029  44.033275
A15 -79.18051   44.056613
A17 -79.057251  44.026426
A8  -79.6297686 44.0395171
B15 -79.180559  44.017748
B9  -79.565778  44.007081
C20 -78.8883705 43.935996

And all I want for my output are pairwise distances, preferably in meters and ability to know what the pairs are. So something like this (please note I made up the distance numbers for now because I couldn’t figure out the distance pairs using my code):

Point1  Point2  Distance
A13     A13     1452.3
A13     A15     562.1
A13     A17     1423
A13     A8      432
A13     B15     673.23
A13     B9      2345
A13     C20     123

The code I used from the geosphere package was:

data <- read.csv(samplepoints.csv, header=TRUE)
points <- data %>% select(GridID, Longitude, Latitude)

geoDist <- distm(as.matrix(points[2:3], fun=distGeo)
df <- data.frame(Distance = geoDist[lower.tri(geoDist)])

But this is what my output looks like:

  Distance
1     11478.59
2     21079.59
3     24837.51
4     11313.88
5     19917.70
6     36278.19

As you can see, I get distances but I have no idea what the pair of points are.

If there is a better package or a better way to calculate this using R, please let me know!

>Solution :

You can directly use the geosphere:distm function, but you have to pass in x and y arguments:

d <- geosphere::distm(df[2:3], df[2:3])
dimnames(d) <- rep(points[1], 2)
as.dist(d)

          A13       A15       A17        A8       B15        B9
A15 11478.585                                                  
A17 21079.586 10433.110                                        
A8  24837.514 36054.251 45916.973                              
B15 11313.877  4318.407  9933.305 36093.157                    
B9  19917.698 31370.861 40832.086  6269.817 30913.208          
C20 36278.193 26994.652 16868.578 60578.756 25142.639 54928.907

If you need in long format do:

dimnames(d) <- rep(points[1], 2)
as.data.frame.table(d,responseName = 'distance')

Leave a Reply