Writing about visualization, demographics, dashboards, and spatial data science.

Interested in learning more? Hire me for a workshop or to consult on your next project. See the Services page for more details.

Fetching roads data in R with tigris

· by Kyle Walker · Read in about 1 min · (212 Words)
R

There are three functions available in the tigris package (https://github.com/walkerke/tigris) to fetch road data. primary_roads() loads all interstates for the entire US; primary_secondary_roads() gets you interstates and US/state/county highways, by state; and roads() gets you all road segments for a given county within a state. In this example, we’ll use the primary_secondary_roads() function to get our data for Route 1 in California.

library(tigris)
library(leaflet)
library(rgdal)
library(geojsonio)
library(widgetframe)

ca <- primary_secondary_roads(state = 'California')

rt1 <- ca[ca$FULLNAME == 'State Rte 1', ]

We can then plot with the leaflet package:

map <- leaflet(rt1) %>% addProviderTiles('CartoDB.Positron') %>% addPolylines()

frameWidget(map)

Using the geojsonio package, we can then write to GeoJSON for use in other applications. Before doing this, I’d advise transforming the coordinate system to WGS84 from NAD83, which is used by all of the Census shapefiles; the two are functionally equivalent, but WGS84 is more universally recognized (e.g. on GitHub).

rt1 <- spTransform(rt1, CRS("+proj=longlat +datum=WGS84"))

geojson_write(rt1, file = 'route1.geojson')

You can view the resultant GeoJSON as a GitHub Gist here: https://gist.github.com/walkerke/c3501f481a780834f8e8

I should note that the primary_secondary_roads() function returns an R object of class SpatialLinesDataFrame with 177 different line segments that collectively make up Route 1. If need be, these segments can be combined with the gLinesMerge function in the rgeos package.