Saturday, 16 February 2019

r - create multipolygon from overlapping polygons using sf package


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




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


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...