How do I map just some of the states in a shapefile in R leaflet.

Hello, i have a shapefile with 47 regions but i only want to map about 15 of the regions(R leaflet).
When adding polygons, I wish to select only the regions I want to map,not all of them.

I suggest you read the shapefile in via {sf} package; the sf objects are modified data frames, meaning you can manipulate them as necessary using the standard {tidyverse} techniques; including dplyr::filter()

Consider this example, using the nc.shp shapefile shipped together with the {sf} package; note the entire content (blue lines) and a selection of two specific counties (red fill).

library(sf)
library(leaflet)
library(dplyr)

nc_all <- st_read(system.file("shape/nc.shp", package="sf")) # shapefile included with sf package

nc_selection <- nc_all %>% 
  filter(NAME %in% c("Graham", "Greene")) # https://en.wikipedia.org/wiki/Graham_Greene :)))


leaflet() %>% 
  addProviderTiles(providers$Stamen.Toner) %>% 
  addPolygons(data = nc_all, # borders of all counties
              color = "blue", 
              fill = NA, 
              weight = 1.5) %>%  
  addPolygons(data = nc_selection, # Graham Greene counties filled in red
              fillColor = "red", 
              color = NA, 
              fillOpacity = .7,
              label = ~NAME)

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.