I have a custom shapefile I put together. It works fine when I plot it all at once. But I'd like to group by certain variables to plot specific shaped regions. For example:

|   county    | region | sales |
| washoe      |      1 |     5 |
| carson city |      1 |    10 |
| clark       |      2 |    15 |
| harmon      |      2 |    20 |

If I run:

leaflet() %>% addTiles %>% addPolygons(data=df)

That will plot four separate polygons based on where those four are located.

But let's say I wanted to create polygons based on regions. So theoretically, the output would contain just two Polygons. One that is the combined shape of montgomery and stevens, and another combining moses and harmon county, and I also want to sum up the total sales.

x <- df %>% group_by(region) %>% summarise(totals=sum(ones))

It will give me this error:

Error in CPL_geos_union(st_geometry(x), by_feature) : 
  Evaluation error: TopologyException: Input geom 0 is invalid: Ring Self-intersection at or near point -119.97497995771261 39.521600907266631 at -119.97497995771261 39.521600907266631

In terms of information on the geometry variable:


Geometry set for 2106 features 
geometry type:  GEOMETRY
dimension:      XY
bbox:           xmin: -115.8968 ymin: 35.00184 xmax: -114.0428 ymax: 36.85366
epsg (SRID):    4326
proj4string:    +proj=longlat +datum=WGS84 +no_defs

Do I need to convert it to something else?

1 Answer 1


There's a problem with (at least) one of your polygons, in that it intersects itself. The border of the polygon isn't a simple ring.

Try narrowing it down by subsetting the data until you find the one (or more) that fails.

Try applying a zero-width buffer using st_buffer to the geometry - this can sometimes fix self-intersections by rebuilding the geometry. Sometimes it works, sometimes it doesn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.