library(sf)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
nc$group <- ifelse(nc$CNTY_ <= 1902, 1,
ifelse(nc$CNTY_ > 1902 & nc$CNTY_ <= 1982, 2,
ifelse(nc$CNTY_ > 1982, 3, NA)))
# Dissolve by group attribute
d <- sf_dissolve(nc, "group")
plot(st_geometry(nc), border="grey")
plot(st_geometry(d), border="red", col=NA,
lwd=2, add=TRUE)
# Dissolve all polygons
d <- sf_dissolve(nc)
plot(st_geometry(nc), border="grey")
plot(st_geometry(d), border="red", col=NA,
lwd=2, add=TRUE)
# Dissolve overlapping polygons
sq <- function(pt, sz = 1) st_polygon(list(rbind(c(pt - sz),
c(pt[1] + sz, pt[2] - sz), c(pt + sz), c(pt[1] - sz, pt[2] + sz),
c(pt - sz))))
pol <- st_sf(box = 1:6, st_sfc(sq(c(4.2,4.2)), sq(c(0,0)), sq(c(1, -0.8)),
sq(c(0.5, 1.7)), sq(c(3,3)), sq(c(-3, -3))))
st_geometry(pol) <- "geometry"
plot(pol)
d <- sf_dissolve(pol, overlaps=TRUE)
plot(d["diss"])
Run the code above in your browser using DataLab