0

I have two datasets: one with 300k + grid points on a map and the other has 75 district centroids. Both datasets have long/latitude of grid points/district centroids. I am trying to match each grid point to each district, such that the grid point's distance to the district centroid <= 100 km. How can I do this in R?

I tried geosphere packages:

merged %>%
  distGeo(c(merged$longitude, merged$latitude), c(geo$centroid_longitude, geo$centroid_latitude))

I also tried distm command but it does not work either.

AndrewGB
  • 16,126
  • 5
  • 18
  • 49
  • "it does not work" is very ambiguous and doesn't give us anything to work with. Was there a syntax error? Were the results wrong? Was it too slow? This sounds doable with a non-equi join as a first pass (possible with the data.table, sqldf, or fuzzyjoin packages, e.g. <0.9 degrees latitude dif means <100km north-south dif) to get potential matches, then a pass where you calculate the distances with distGeo and filter for just the ones you want. – Jon Spring Jan 05 '22 at 22:35
  • Thanks a lot. I keep getting messages like "Error in .pointsToMatrix(p2) : Wrong length for a vector, should be 2" and etc. I think the issue is I have 75 districts for the 300K + grid points to match. So I am not sure how I match them one by one to figure out which grid point belongs to which district i.e. distance <= 100 – chris z Jan 05 '22 at 22:42
  • You probably need to apply the calculation after `rowwise() %>%`, like here: https://stackoverflow.com/q/40554592/6851825 – Jon Spring Jan 05 '22 at 23:03

1 Answers1

0

First: What do you want to do with grid points that are within 100 km of several districts?

Why not buffer the district centroids, then do a spatial join with the grid points?

library(sf)
# Assuming your layers are in a meter based CRS
district_buffers <- st_buffer(district_centroids, dist=100000)
merged <- st_join(grid_points, district_buffers)

Now the merged sf point layer will have the attributes of the district buffer that it intersects.

Micha
  • 403
  • 2
  • 13