I am attempting to make a choropleth using leaflet. I downloaded a shapefile of ZCTAs from data.gov and imported it into R via readOGR. Then, when piping that file into leaflet, nothing happens.
I think the issue may be that the lats and lons from the shapefile are being imported as factors instead of numerics? Except when I try to convert those variables into numerics, I am returned with the error:
Error in `$<-.data.frame`(`*tmp*', lat, value = numeric(0)) : replacement has 0 rows, data has 33144
On the other hand, that is only a guess and I am brand new to leaflet and mapping in general; I am still learning which way is up.
Here is my code:
shape <- readOGR(dsn = path.expand("//cifs2/radonfin$/MaxG/In Progress/Geographical Capture/Shape Files"),
layer = "tl_2018_us_zcta510")
shape@data$GEOID10 = as.numeric(as.character(shape@data$GEOID10))
colnames(shp_Patients_by_ZCTA)[colnames(shp_Patients_by_ZCTA)=="INTPTLAT10"] <- "lat"
colnames(shp_Patients_by_ZCTA)[colnames(shp_Patients_by_ZCTA)=="INTPTLON10"] <- "lng"
shape %>%
leaflet(options = leafletOptions( minZoom = 8,
maxZoom = 12,
dragging = TRUE)) %>%
addProviderTiles("CartoDB.PositronNoLabels", group = "Light Mode") %>%
addProviderTiles("CartoDB.DarkMatterNoLabels", group = "Dark Mode") %>%
addPolygons() %>%
setView(lng = -71.808206, lat = 42.016621, zoom = 8) %>%
setMaxBounds(lng1 = -73.561893,
lat1 = 42.855596,
lng2 = -69.889730,
lat2 = 41.001180) %>%
addMarkers(data = Hospital_Locations,
lat = Hospital_Locations$Latitude,
lng = Hospital_Locations$Longitude,
label = Hospital_Locations$Location) %>%
addLayersControl(baseGroups = c("Light Mode", "Dark Mode"),
overlayGroups = c("Boston", "Mansfield", "Milford", "Saint Anne's"))
My expect result is a leaflet map with the polygons described by the shapefile, but the actual results are that either:
I get an error when converting
lat
andlon
into numerics; or if I skip that,R freezes until I stop the code.
I really appreciate any help you can lend!!