How to calculate distance between coordinates (for multiple rows)?

Hello,

R has a built in function to easily calculate the distance matrix from a set of coordinates like this:

set.seed(1) #For reproducibility only

#Data with x and y coords
points = data.frame(x = runif(5), y = runif(5))
points
#>           x          y
#> 1 0.2655087 0.89838968
#> 2 0.3721239 0.94467527
#> 3 0.5728534 0.66079779
#> 4 0.9082078 0.62911404
#> 5 0.2016819 0.06178627

#Distance matrix
dist(points, method = "euclidean", upper = T, diag = T)
#>           1         2         3         4         5
#> 1 0.0000000 0.1162289 0.3884722 0.6968296 0.8390346
#> 2 0.1162289 0.0000000 0.3476762 0.6220650 0.8991904
#> 3 0.3884722 0.3476762 0.0000000 0.3368478 0.7046865
#> 4 0.6968296 0.6220650 0.3368478 0.0000000 0.9061124
#> 5 0.8390346 0.8991904 0.7046865 0.9061124 0.0000000

Created on 2022-03-06 by the reprex package (v2.0.1)

Hope this helps,
PJ

1 Like