R SF – How to Create Multipolygon from Overlapping Polygons Using sf Package in R

data-framepolygonrsf

I'm trying to remove overlapping areas from multiple polygons using sf like the following:

# sample polygon
poly <- data.frame(
    lon = c(0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 2, 2, 0.8, 1, 1, 2, 2, 1, 1),
    lat = c(0, 0, 1, 1.5, 0, 1, 1, 2, 2, 1, 1, 1, 2, 2, 1, 0, 0, 1, 1, 0),
    var = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3 ,3 ,3 ,3 ,3, 4 ,4 ,4, 4, 4)
  ) %>%
  st_as_sf(coords = c("lon", "lat"), dim = "XY") %>% st_set_crs(4326) %>% 
group_by(var) %>%
  summarise(geometry = st_union(geometry), do_union = F) %>% st_cast("POLYGON")

In my data there are several hundred polygons and many of them are overlapping multiple times. So it would be great if there is a way to remove overlapping areas from a sf dataframe like in the example. I tried something with st_difference but I thought there might be a better way than applying this to each pair of polygons which would result in too many permutations.

enter image description here

Best Answer

You can do the intersection of polygons and then filter those that overlap.

inter <- st_intersection(poly) %>% filter(n.overlaps < 2)
plot(inter %>% select(var)

enter image description here