I received a file of municipality boundaries, where the boundaries are represented as lines. I would like to convert this to a set of polygons, each representing a municipality. In other words, from a set of lines, I would like to create the highest number of non-overlapping polygons.
I would like to do this in R (currently using the
sf package, but could use another). I believe the correct command is
st_polygonize, however the data does not seem to be extremely high quality, so some of the lines do not exactly touch (for one pair, I calculated the distance between the endpoints as 1.77e-15 meters). There are also holes in the municipalities.
st_polygonizethe correct command? I only have one observation for each line segment, but a single line segment can belong to multiple municipalities. Whoever created this file seems to have done it in a way so that each line segment belongs to at most 2 municipalities, but I do not know how to verify this.
- How do I deal with the fact that not all line segments will touch?
st_polygonizedoes not seem to have a tolerance parameter, is there some other command I can use?
I solved the tolerance issue via the following:
st_line_sample(line, sample = c(0,1)) to find the endpoints of each line. I then calculated pairwise distances between all endpoints using
st_distance and filtered for distances that were greater than 0 and less than a tolerance number. The next part requires some manual work, but using the filtered distances, one can identify which line segments are misaligned. I then used
st_snap to snap these line segments to each other. With the new snapped line segments, I can then create the polygons as per Spaceman's answer below.