Fetching roads data in R with tigris

December 2, 2015

(This article was first published on KYLE WALKER DATA, and kindly contributed to R-bloggers)

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.


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()


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.

To leave a comment for the author, please follow the link and comment on their blog: KYLE WALKER DATA.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)