I'm trying to dissolve shapefile boundaries based on an attribute. I want to combine many smaller polygons so that the result is a series of polygons which are composed of the outside boundaries of the smaller ones. I have tried to do this in R in a number of ways including:


my_file <- readOGR("./my_path/my_file.shp")
groups = aggregate(my_file, by = "my_attribute")
my_file <- readOGR("./my_path/my_file.shp")
my_file_fortified <- fortify(my_file, region = "my_attribute")
# merge the "fortified" data with the data from our spatial object
my_df<- merge(my_file_fortified, my_file@data, by.x = "id", by.y = "my_attribute")
  1. my_file <- read_sf("./my_path/my_file.shp") st_union_by = function(geo, group) { # browser() geo group

       y2 = list()
        #loop over by groups and merge units
          for (i in unique(group)) {
            #which units
                z = geo[group == i]
              y = Reduce(st_union, z)
              y2[[i]] = y


    my_file <- st_union_by(my_file$geometry, my_file$my_attribute)

taken from here: Using sf to combine polygons that share borders? which results in this error: Error in CPL_geos_op2(op, x, y) : Evaluation error: TopologyException: Input geom 0 is invalid: Ring Self-intersection at or near point -122.33666229315305 47.540180206469273 at -122.33666229315305 47.540180206469273.

The rest result in a map which looks like this: enter image description here

Why are the broken lines bits in the polygons, and how to dissolve polygons without creating these? This is the data and I am trying to combine based on the PROVCODE column.

  • 1
    Search the old questions (polygon dissolve/union/merge), you may find something useful. For example gis.stackexchange.com/questions/71612/…. The reason is that shapefile is not a topological format. Each polygon is an own shape and nothing guarantees that the common boundaries of adjacent polygons share the same vertices. Zoom very close to the places where you have those small lines and you will find small gaps and overlaps. – user30184 Apr 23 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.