I'm currently working on 31 different multipolygon shapefiles for which I need to generate a minimal distance to the nearest polygon "ANPs" (which is a multipolygon itself). I haven't been able to do it easily. I have had to modify the crs of the "ANPs" shapefile and disband the multipolygons in order to obtain individual polygons and then finding the closest neighbor and calculate minimal distance for it.
In the picture, you can see some of the 31 polygon shapefiles and the centroids of the "ANPs" shapefile. For each district, I want to generate the minimal distance for the closest blue dot.
I haven't been able to come up with an iterative/loop function to do this code automatically, but here is what I have came up with for:
`st_crs(ANPs) #returns, "MEXICO_ITRF_2008"
st_crs(DISTAgs) #returns, "WGS 84 / UTM zone 13N"
ANPs_84=st_transform(ANPs, 32613) #transforms to WGS 84 to UTM zone 13 N.
ANPs= st_cast(ANPs_84, "POLYGON") #disbanding to polygons.
DISTAgs=st_cast(DISTAgs, "POLYGON")
##disbanding ANPs results in the following error message.
##In st_cast.sf(ANPs, "POLYGON") :
## repeating attributes for all sub-geometries for which they may not be constant
ANPsc=st_centroid(ANPs) #calculating centroids.
DISTAgsc=st_centroid(DISTAgs)
st_nearest_feature(DISTAgsc, ANPsc) #nearest feature`
And that's as far as I got.
So, Should I worry about the multiple polygons generated by st_cast? (I think not because they are labeled). Is there an interative way to do this for all the other DISTx shapefiles? Will this be to innacurate?
DISCLAIMER: I'm new to cartography, GIS and more or less to RStudio.
MULTIPOLYGON
toPOLYGON
and also don't have to calculate the centroids. Functionst_distance
gives the shortest distance to the nearest boundary point between (MULTI)POLYGONs. Sost_distance(ANPs, DISTAgs)
should do, returning a distance matrix of shortest distances between each pair of features in the two layers. For more specific example, please share a sample of the data you are working with.GEODIST
a 300 row data frame that encapsulates the geometries to analyze. I've also have created an index to order theANPs
geometries to match theANPs
nearest observation for eachGEODIST
observation. With that in mind, I generatedst_distance(GEODIST, ANPs, by_element=TRUE)
but it has taken around 11 hours without giving a result? I based this operation on this question: stackoverflow.com/questions/53854803/….