...how i can match the nearest ingroup and outgroup upto 5 kms , i want to incorporate the distance between ingroup and outgroup please guide
Reprex
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(leaflet)
library(charlatan)
# somewhere in pakistan...
ingroup <- data.frame(matrix(c(lat=33.74, lon=73.17), ncol = 2, byrow = F)) %>%
mutate(name = ch_name(1)) %>%
st_as_sf(coords = c("X1","X2"), crs=4326)
ingroup
#> Simple feature collection with 1 feature and 1 field
#> geometry type: POINT
#> dimension: XY
#> bbox: xmin: 33.74 ymin: 73.17 xmax: 33.74 ymax: 73.17
#> geographic CRS: WGS 84
#> name geometry
#> 1 Winston Shanahan POINT (33.74 73.17)
# somewhere else in pakistan...
outgroup <- data.frame(matrix(c(lat=33.60,lon=73.01), ncol = 2, byrow = F)) %>%
mutate(name = ch_name(1)) %>%
st_as_sf(coords = c("X1","X2"), crs=4326)
outgroup
#> Simple feature collection with 1 feature and 1 field
#> geometry type: POINT
#> dimension: XY
#> bbox: xmin: 33.6 ymin: 73.01 xmax: 33.6 ymax: 73.01
#> geographic CRS: WGS 84
#> name geometry
#> 1 Averie Zboncak POINT (33.6 73.01)
# find the nearest neighbour: sf::st_nearest_feature (computationally very efficient)
ingroup <- ingroup %>%
mutate(nearest_out = outgroup$name[st_nearest_feature(., outgroup)]) %>%
mutate(label = paste0("ingroup: <b>", name, "</b><br>nearest outgroup is: ", nearest_out))
#> although coordinates are longitude/latitude, st_nearest_points assumes that they are planar
# And now visualize the stuff!
leaflet() %>%
addTiles() %>%
addCircleMarkers(data=ingroup,lng=73.17,lat= 33.74,
fillColor = "red",
stroke = F,
fillOpacity = .8,
popup = ~label) %>%
addCircleMarkers(data=outgroup,lng=73.01,lat= 33.60,
fillColor = "blue",
stroke = F,
fillOpacity = .8,
popup = ~name)%>%
addMarkers(lng=store$long,lat= store$lat,popup = "store ",group = "2")
#> Error in resolveFormula(lng, data): object 'store' not found