R – Using st_overlaps to Subset Fully Covered Polygons in R Spatial

gdaloverlapping-featuresrrgdalsp

I want to subset all polygons in fc1 completely or partially overlapping with fc2. But, the st_overlaps subsets only polygons that overlaps with the border of fc2, but skips the fully covered polygons. I.e. here: polygons in center (grey) are not subsetted, only red polygons are returned as overlapped:

enter image description here

I wonder if there is a way how to subset all – partially and fully covered – polygons at once? Is really the only option to subset polygons twice: by st_covers and st_overlaps and then combine them? Would not this approach lead to duplicated polygons?

My dummy example:

# Load data
shp = system.file("shape/nc.shp", package="sf")    
my.sf <- st_read(shp, quiet = TRUE)

# Convert crs to projected system to make buffer
my.sf.web<- st_transform(my.sf, 3857)

# Subset one polygon
i = 10
one  = my.sf.web[i, ]

# Create buffer 
buff50 = st_buffer(one, 50000)

# Check which polygons overlaps with my buffer
out.overlap = st_overlaps(buff50, my.sf.web)

# Subset the polygons that overlaps with the buffer
nbrs.buff.over  <- my.sf.web[st_overlaps(buff50,my.sf.web)[[1]],]
nbrs.buff.cover <- my.sf.web[st_covers(buff50,my.sf.web)[[1]],]

# Merge both spatial subsets:  # !!! Is there easier and less error prone solution??
out <- cbind(nbrs.buff.over, nbrs.buff.cover)

I expect that my output will contain all – completely and fully covered polygons.

Best Answer

Use st_intersects() instead of st_overlaps(). You only got 9 features, because st_overlaps() does not return features that are completely contained by the other geometry.

out.overlap <- my.sf.web[st_intersects(buff50, my.sf.web, sparse =  FALSE),]

With this you should have your 11 polygons that you want. In this case the sf-cheat sheet which you can find here: https://rstudio.com/resources/cheatsheets/ is quite helpful, to exactly now which operation does what.

Related Question