So finding the union of a more than two polygons turns out to be straight forward using st_union and group_by() from dplyr. Finding the intersection with st_intersection turns out to not be as simple since st_intersection does only work for finding intersection of two objects. What's the best way to find the intersection of multiple polygons by group? Here's some example data
s1 <- rbind(c(1, 1), c(10, 1), c(10, 10), c(1, 10), c(1, 1))
s2 <- s1 + 4
s3 <- s1 - 4
group <- c(rep(1, 3), rep(2, 3))
df <- data.frame("group" = c(rep(1, 3), rep(2, 3)))
df <- data.frame(cbind(df, rep((c(st_sfc(st_polygon(list(s1))), st_sfc(st_polygon(list(s2))), st_sfc(st_polygon(list(s3))))), 2)))
What I want is to replace the geometry column with the intersection in each group, that is the object created by
p <- list(s1 = s1, s2 = s2, s3 = s3)
p <- lapply(p, function(x) st_sfc(st_polygon(list(x))))
intersection <- accumulate(p, st_intersection)$s3
intersection <- st_sfc(st_polygon(intersection))
So the final data would look like
df <- data.frame("group" = c(rep(1, 3), rep(2, 3)))
df <- data.frame(st_sf(cbind(df, rep(st_sfc(st_polygon(intersection)), 6))))