Search code examples
rdplyrr-sfr-leaflet

How to make Multipolygons with Package SF and dplyr


How can I use dplyr to collapse an sf map object into multipolygons geometry?

When I use group_by and summarise, the default resultant geometry appears to be a MULTIPOINT sfg class. I am looking to plot 3 distinct polygons (1 for each 'area' value) with package leaflet from the dummy data below.

Any guidance would be mightily appreciated thanks.

library(tidyverse)
library(sf)
library(leaflet)

wannabe_polygons <- st_as_sf(tibble(
  area =c(rep("southern suburbs", 8),
      rep("northern suburbs", 6),
      rep("somerset west", 5)
      ),
  lng = c(18.35, 18.37, 18.34, 18.45,
      18.49, 18.43, 18.42, 18.32,
      18.49, 18.48, 18.44, 18.7,
      18.74, 18.72, 18.82, 18.89,
      18.92, 18.87, 18.7
  ),
  lat = c(-34.1, -34.06, -33.99, -33.97,
      -34.09, -34.14, -34.19, -34.15,
      -33.88, -33.83, -33.7, -33.8,
      -33.9, -34.07, -33.9, -33.9,
      -34.11, -34.16, -34.05
  )

),
coords = c("lng", "lat"))

wannabe_polygons <- wannabe_polygons %>% 
  group_by(area) %>% 
  summarise()

# str(wannabe_polygons)

leaflet() %>% 
  addTiles(group = "OSM") %>% 
  addPolygons(data = wannabe_polygons)

Solution

  • Not sure why you want to convert to MULTIPOLYGON but here's how you do it:

    
    wannabe_polygons %>%
      group_by(area) %>%
      summarise(geometry = st_combine(geometry)) %>%
      st_cast("POLYGON") %>%
      summarise(geometry = st_combine(geometry)) -> new_polygons
    
    leaflet() %>% 
      addProviderTiles(providers$OpenStreetMap) %>% 
      addPolygons(data = new_polygons)
    
    

    If you use MULTIPOLYGON or POLYGONwill make no difference in the resulting leaflet map, so you may just stop after st_cast("POLYGON").