Subsetting the neighborhoods
You don't need all those extraneous neighborhoods in New York, so you'll subset out just the neighborhoods in New York County. You already know how!
neighborhoods is a SpatialPolygonsDataFrame and you learned back in Chapter 2 how to subset based on the column in the data slot. The key was creating a logical vector, then subsetting the SpatialPolygonsDataFrame like a data frame.
How can you identify the right neighborhoods? Check out:
head(neighborhoods@data)
The CountyFIPS is a numeric code that identifies the county. If you can figure out the code for New York County, you can keep just the rows with that value.
This exercise is part of the course
Visualizing Geospatial Data in R
Exercise instructions
- The
nyc_tracts_mergeobject also has country codes in the columnCOUNTYFP. Find theunique()values to find the code for New York County. - Subset
neighborhoodsby adding a logical that tests ifneighborhoods$CountyFIPShas the right value. - Edit your plot to use
manhat_hoodsinstead of neighborhoods. - Add a
tm_text()layer, mappingtextto"NTAName".
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
library(tmap)
# Find unique() nyc_tracts_merge$COUNTYFP
# Add logical expression to pull out New York County
manhat_hoods <- neighborhoods[___, ]
tm_shape(nyc_tracts_merge) +
tm_fill(col = "estimate") +
tm_shape(water) +
tm_fill(col = "grey90") +
# Edit to use manhat_hoods instead
tm_shape(neighborhoods) +
tm_borders() +
# Add a tm_text() layer