2

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)
CallumH
  • 751
  • 1
  • 7
  • 22

1 Answers1

1

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").

Humpelstielzchen
  • 6,126
  • 3
  • 14
  • 34
  • thanks @humpelstielzchen. It was the st_cast step i was missing. – CallumH Jun 12 '19 at 11:56
  • You're welcome! The trick however is `st_combine()`, if you just cast `MULTIPOINT` your polygons end up messy. – Humpelstielzchen Jun 12 '19 at 12:07
  • This code will generate a single MULTIPOLYGON feature (`new_polygons` has one row). The data form three overlapping rings that can't be represented as a single POLYGON feature, so leaflet would have to see three POLYGON features - this would make a difference to the leaflet map in terms of further styling and interactivity. – Spacedman Jun 16 '19 at 16:10