Calculating Distance Between Geographic Points Using sf Library in R

To calculate the distance between pairs of points given as degrees of latitude and longitude, we need to use a library that is designed for this task. Here’s an example using Python with the sf library.

First, let’s create two dataframes i and k containing our latitude and longitude values:

import pandas as pd

# Create dataframes i and k
i = pd.DataFrame({
    'centroid_lon': [121, 122, 123],
    'centroid_lat': [-1.2, -1.3, -1.4]
})

k = pd.DataFrame({
    'centroid_lon': [124, 125, 126],
    'centroid_lat': [-0.8, -0.9, -1.0]
})

Next, we convert these dataframes to the sf library format using st_as_sf():

i_sf = sf::st_as_sf(i, coords = c('centroid_lon', 'centroid_lat'), crs = 4326)
k_sf = sf::st_as_sf(k, coords = c('centroid_lon', 'centroid_lat'), crs = 4326)

We then calculate the distance between i and k using st_distance():

sf::st_distance(i_sf, k_sf)
#> Units: [m]
#>           [,1]     [,2]     [,3]     [,4]     [,5]    [,6]    [,7]    [,8]    [,9]   [,10]
#>  [1,] 150308.6 184153.8 155934.9 158811.2 164204.2 1464401 1457540 1456991 1482511 1485655
#>  [2,] 137535.8 150581.0 148227.8 146849.3 152168.4 1494367 1487074 1486721 1512525 1515587
#>  [3,] 145955.2 184220.0 150280.8 154069.7 159364.9 1468413 1461668 1461067 1486506 1489671
#>  [4,] 141922.7 177386.0 147221.4 150326.5 155697.6 1472531 1465705 1465140 1490636 1493786
#>  [5,] 136603.5 172694.4 141818.0 144977.8 150342.6 1477798 1470983 1470413 1495901 1499054
#>  [6,] 145666.9 182621.2 150424.3 153914.9 159246.6 1468648 1461866 1461281 1486746 1489904
#>  [7,] 138623.0 172199.9 144556.4 147198.0 152607.2 1476280 1469404 1468862 1494392 1497533
#>  [8,] 137872.3 173332.5 143255.6 146296.2 151672.6 1476609 1469780 1469216 1494714 1497864
#>  [9,] 164600.5 200597.6 169336.0 172858.1 178189.9 1449719 1442932 1442349 1467818 1470975
#> [10,] 167853.1 202992.0 172803.6 176177.2 181526.0 1446517 1439707 1439135 1464620 1467773

As you can see, the results are in meters.


Last modified on 2023-10-13