Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find how many locations near a radius of 250 meters

I have the following dataframe:

df <- tribble(~ id,       ~ lon,              ~ lat,
                 1, -56.2112038,         -34.8358207,
                 2, -55.96403429999999,  -34.7260945,
                 3, -56.155449,          -34.9030824,
                 4, -55.2711453,         -34.8665964,
                 5, -56.210083,          -34.865306,
                 6, -56.0575984,         -34.8775368,
                 7, -54.9485448,         -34.9260087,
                 8, -56.146228,          -34.907991,
                 9, -56.1953583,         -34.8643363,
                 10, -56.1821508,        -34.8697975,
                 11, -56.1498662,        -34.8849854,
                 12, -56.1469807,        -34.9119864,
                 13, -56.155763,         -34.9154153,
                 14, -56.09861610000001, -34.8896448,
                 15, -56.15526680000001, -34.9189892,
                 16, -56.0582918,        -34.8873091,
                 17, -54.9529404,        -34.9221666,
                 19, -106.6971588,       -35.1366719,
                 20, -56.1616095,        -34.8937622)

What I want to achieve is adding a new column that says how many ids are within a radius/distance of 250 meters of each other. The idea is to take one row, "look" at the coordinates, and see if that point is within a radius of 250 meters of the other ids and how many of them.

like image 277
Paula Avatar asked Jun 16 '21 10:06

Paula


1 Answers

library(tidyverse)
library(sf)

You should probably transform coordinates to 31972 (Latin America, https://epsg.io/31972)

df_sf <- df %>% 
  st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
  st_transform(31972)
circle_df <- df_sf %>% st_buffer(250)

df[["close_id"]] <- st_within(df_sf, circle_df) %>% imap(setdiff)
df[["n"]] <- df[["close_id"]] %>% map_int(length)

you can see that minimum distance between your points is:

st_distance(df_sf) %>% .[. > units::set_units(0, "meters")] %>% min()
413.7485 [m]
like image 54
det Avatar answered Nov 13 '22 12:11

det