Getting data using a package
Reading in spatial data from a file is one way to get spatial data into R, but there are also some packages that provide commonly used spatial data. For example, the rnaturalearth
package provides data from Natural Earth, a source of high resolution world maps including coastlines, states, and populated places. In fact, this was the source of the data from Chapter 2.
You will be examining median income at the census tract level in New York County (a.k.a. the Bourough of Manhattan), but to do this you'll need to know the boundaries of the census tracts. The tigris
package in R provides a way to easily download and import shapefiles based on US Census geographies. You'll use the tracts()
function to download tract boundaries, but tigris
also provides states()
, counties()
, places()
and many other functions that match the various levels of geographic entities defined by the Census.
Let's grab the spatial data for the tracts.
This exercise is part of the course
Visualizing Geospatial Data in R
Exercise instructions
- Call
tracts()
withstate = "NY"
,county = "New York"
, andcb = TRUE
. Store the result innyc_tracts
. - Use
summary()
onnyc_tracts
to verify the retuned object is aSpatialPolygonsDataFrame
. - Plot
nyc_tracts
to check the contents withplot()
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
library(sp)
library(tigris)
# Call tracts(): nyc_tracts
# Call summary() on nyc_tracts
# Plot nyc_tracts