Fetching roads data in R with tigris

[This article was first published on Kyle Walker, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

To leave a comment for the author, please follow the link and comment on their blog: Kyle Walker.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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)