6
votes

I'm currently trying to map all the zip codes in North Carolina onto a leaflet map. Ultimately, I'd like to color-code these with values from another data-set.

While I've managed to put markers onto the map with these values, doing so in a colorized fashion with zip-codes would really add value to my project.

I downloaded the USAboundaries library in R, and so I think I have enough data to create the polygons in leaflet, but the data is not in the SpatialPointsDataFrame format.

The sample output from the USAboundaries dataset looks like this:

USAboundaries::us_zipcodes()

Simple feature collection with 33144 features and 6 fields
geometry type:  POINT
dimension: XY
bbox:  
 xmin: -176.6316 
 ymin: -14.22075 
 xmax: 145.7536 
 ymax: 71.2738

epsg (SRID):    4326

proj4string:    +proj=longlat +datum=WGS84 +no_defs

First 10 features:
  zipcode zcta5ce10     affgeoid10 geoid10   aland10 awater10                   geometry
    21914     21914 8600000US21914   21914   1924479   477175 POINT (-75.98187 39.57303)
    01001     01001 8600000US01001   01001  29731610  2118827 POINT (-72.62585 42.06258)
    34736     34736 8600000US34736   34736 322808220 78588518 POINT (-81.89624 28.55458)
    46151     46151 8600000US46151   46151 530632048  9804480  POINT (-86.4305 39.44806)
    48039     48039 8600000US48039   48039  59592687  4845242 POINT (-82.55054 42.69666)

In my mind, this should be enough to transform into a SpatialPointsDataFrame, but I don't know how to do it in R! Any tips would be greatly appreciated!

1

1 Answers

4
votes

Leaflet supports sf objects, therefore you should not experiment any problem. Nevertheless, you can transform a sf object to a sp (such as Spatial Points Data Frame) with as(YourObject, "Spatial"). For change from sp to sf you use as_as_sf

library(sf)
library(sp)
data(meuse)
coordinates(meuse) = ~x+y
m.sf = st_as_sf(meuse) 
x = st_sfc(st_point(c(5,5)), st_point(c(6,9)), crs = 4326)
as(x, "Spatial")

See this