Search code examples
rgeojsonshapefiler-sf

Merging some of the polygon boundaries using sf in R


I am trying to plot the boundaries from this geojson file.

I am able to plot all the boundaries using sf in R. However, I would like to merge some polygons together - e.g., POL_STN_NM = PS RAJ PARK, PS SULTAN PURI, PS MANGOL PURI - should be plotted as having one area.

However, using st_union is not removing the internal boundaries.

Could someone please help me with this? I am new to spatial mappings.

Thank you! :)


Solution

  • First ring of that union is an exterior ring, you can extract it and turn it to polygon & sfc to get a polygon without holes:

    library(sf)
    #> Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
    library(dplyr)
    
    pls <- st_read("https://gist.githubusercontent.com/Vonter/a1f0f9d50a587ce059ddcfb086fc0fac/raw/fcf1b53987b15bb9ee37820e655ae874b8e214fa/Police%2520Station%2520Boundary.geojson")
    with_holes <- pls[pls$POL_STN_NM %in% c("PS RAJ PARK", "PS SULTAN PURI", "PS MANGOL PURI"), ] |>
      st_union()
    ext_ring <- st_polygon(with_holes[[1]][1]) |> st_sfc(crs = st_crs(pls))
    
    par(mfrow=c(1,2))
    plot(with_holes)
    plot(ext_ring)
    

    Created on 2023-05-13 with reprex v2.0.2

    For some additional context:

    POLYGON : geometry with a positive area (two-dimensional); sequence of points form a closed, non-self intersecting ring; the first ring denotes the exterior ring, zero or more subsequent rings denote holes in this exterior ring
    https://r-spatial.github.io/sf/articles/sf1.html#simple-feature-geometry-types

    Simple feature geometries are implemented as R native data, using the following rules

    1. a single POINT is a numeric vector
    2. a set of points, e.g. in a LINESTRING or ring of a POLYGON is a matrix, each row containing a point
    3. any other set is a list

    https://r-spatial.github.io/sf/articles/sf1.html#sfg-simple-feature-geometry