Finding shortest distance between two sets of points ( latitude and longitude) points in R

Solution 1:

Please find one possible solution using sf, units, dplyr and tmap libraries

Reprex

  • Computing the distance matrix (distance in km)
library(sf)
library(units)
library(dplyr)
library(tmap)

# Convert the two dataframes into 'sf' objects

control_sf <- st_as_sf(control, coords = c("longitude", "latitude"), crs = 4326)

treatment_sf <- st_as_sf(treatment, coords = c("longitude", "latitude"), crs = 4326)


# Compute a distance matrix (distance in km)
# rows = control
# columns = treatment
Distances_df <- control_sf %>% 
  st_distance(., treatment_sf) %>% 
  set_units(., km) %>% 
  drop_units() %>% 
  round(., 1) %>% 
  as.data.frame() %>% 
  setNames(., treatment$id) %>% 
  mutate(control = control$id) %>% 
  relocate(control)

Distances_df
#>         control 110000308881 110000310556 110000314570 110000316024
#> 1  110000308033         92.0        114.9        481.6         79.4
#> 2  110000308042         91.9        114.5        481.6         78.8
#> 3  110000308060         92.8        115.2        482.6         78.7
#> 4  110000308346         91.5        109.7        483.6         70.5
#> 5  110000308505        120.9        164.9        475.8        144.3
#> 6  110000308541        147.5        176.9        521.6        128.6
#> 7  110000308612         61.0        107.2        436.4        112.0
#> 8  110000309684         39.1         51.5        371.0        133.4
#> 9  110000309773         56.2         65.2        353.4        151.3
#> 10 110000309835         39.7         59.5        364.6        140.0
#>    110000324845
#> 1         148.9
#> 2         149.6
#> 3         149.7
#> 4         157.9
#> 5          84.5
#> 6         120.9
#> 7         129.1
#> 8         215.4
#> 9         226.7
#> 10        212.0
  • Visualization (control in blue and treatment in red)
tmap_mode("view")
#> tmap mode set to interactive viewing

tm_shape(control_sf) +
  tm_dots(col = "blue")+
  tm_shape(treatment_sf) +
  tm_dots(col = "red")

enter image description here

Created on 2022-01-14 by the reprex package (v2.0.1)