Learn R Programming

⚠️There's a newer version (1.2.2) of this package.Take me there.

stplanr

This package is for sustainable transport planning with R (hence the name stplanr).

It brings together a range of tools for transport planning practitioners and researchers to better understand transport systems and inform policy.

The initial work on the project was funded by the Department of Transport (DfT) as part of the Propensity to Cycle Tool (PCT) project to identify where bicycle paths are most urgently needed. Please see the package vignette or an academic paper on the PCT for more information on how it can be used. This README gives some basics.

stplanr should be useful to researchers everywhere. The function route_graphhopper(), for example, works anywhere in the world using the graphhopper routing API and read_table_builder() reads-in Australian data. We welcome contributions that make transport research easier worldwide.

Key functions

Data frames representing flows between origins and destinations must be combined with geo-referenced zones or points to generate meaningful analyses and visualisations of 'flows' or origin-destination (OD) data (Caceres 2007). stplanr facilitates this with od2line(), which takes flow and geographical data as inputs and outputs a SpatialLinesDataFrame. Some example data is provided in the package:

library(stplanr)
data(cents, flow)

Let's take a look at this data:

flow[1:3, 1:3] # typical form of flow data
#>        Area.of.residence Area.of.workplace All
#> 920573         E02002361         E02002361 109
#> 920575         E02002361         E02002363  38
#> 920578         E02002361         E02002367  10
cents[1:3,] # points representing origins and destinations
#> class       : SpatialPointsDataFrame 
#> features    : 3 
#> extent      : -1.546463, -1.511861, 53.8041, 53.81161  (xmin, xmax, ymin, ymax)
#> coord. ref. : +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 
#> variables   : 4
#> names       :  geo_code,  MSOA11NM, percent_fem,  avslope 
#> min values  : E02002382, Leeds 053,    0.408759, 2.284782 
#> max values  : E02002393, Leeds 064,    0.458721, 2.856563

These datasets can be combined as follows:

travel_network <- od2line(flow = flow, zones = cents)
w <- flow$All / max(flow$All) *10
plot(travel_network, lwd = w)

The package can also allocate flows to the road network, for example through a link to the CycleStreets.net API.

Route functions take lat/lon inputs:

trip <-
  route_cyclestreet(from = c(-1, 53), to = c(-1.1, 53), plan = "balanced")

and place names, found using the Google Map API:

trip <- route_cyclestreet("London", "Birmingham, UK", plan = "balanced")
# devtools::install_github("mtennekes/tmap", subdir = "pkg")
library(tmap)
osm_tiles <- read_osm(bb(bbox(trip), ext = 1.5))
tm_shape(osm_tiles) +
  tm_raster() +
  tm_shape(trip) +
  tm_lines(lwd = 3)

We can replicate this call to CycleStreets.net multiple times using line2route.

# Remove intra-zone flow
intrazone <- travel_network$Area.of.residence == travel_network$Area.of.workplace
travel_network <- travel_network[!intrazone,]
t_routes <- line2route(travel_network)
plot(t_routes)

Another way to visualise this is with the leaflet package (not shown):

library(leaflet)
leaflet() %>% addTiles() %>% addPolylines(data = t_routes)

For more examples, example("line2route").

overline is a function which takes a series of route-allocated lines, splits them into unique segmentes and aggregates the values of overlapping lines. This can represent where there will be most traffic on the transport system, as illustrated below using the tmap package.

t_routes$All <- travel_network$All
rnet <- overline(sldf = t_routes, attrib = "All", fun = sum)

osm_tiles <- read_osm(bb(rnet, ext = 1.05))
rnet$lwd <- rnet$All / mean(rnet$All)
tm_shape(osm_tiles) +
  tm_raster(saturation = .25) +
  tm_shape(rnet) +
  tm_lines(lwd = "lwd", scale = 5, legend.lwd.show = FALSE)  +
  tm_shape(cents) +
  tm_bubbles()

Installation

To install the stable version, use:

install.packages("stplanr")

The development version can be installed using devtools:

# install.packages("devtools") # if not already installed
devtools::install_github("ropensci/stplanr")
library(stplanr)

stplanr depends on rgdal, which can be tricky to install.

Installing rgdal on Ubuntu and Mac

On Ubuntu rgdal can be installed with:

sudo apt-get install r-cran-rgdal

Using apt-get ensures the system dependencies, such as gdal are also installed.

On Mac, homebrew can install gdal. Full instructions are provided here.

Funtions, help and contributing

The current list of available functions can be seen with:

lsf.str("package:stplanr", all = TRUE)

To get internal help on a specific function, use the standard way.

?od2line

Meta

  • Please report issues, feature requests and questions to the github issue tracker
  • License: MIT
  • Get citation information for stplanr in R doing citation(package = 'stplanr')
  • This project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

Copy Link

Version

Install

install.packages('stplanr')

Monthly Downloads

1,827

Version

0.1.4

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Last Published

August 29th, 2016

Functions in stplanr (0.1.4)

calc_catchment_sum

Calculate summary statistics for catchment area.
calc_moving_catchment

Calculate summary statistics for all features independently.
bbox_scale

Scale a bounding box
calc_catchment

Calculate catchment area and associated summary statistics.
calc_network_catchment

Calculate catchment area and associated summary statistics using network.
dl_stats19

Download Stats19 data
format_stats19_ca

Format UK 'Stats19' road traffic casualty data
dist_google

Return travel network distances and time using the Google Maps API
flowlines

SpatialLinesDataFrame of commuter flows
flow

data frame of commuter flows
cyclestreet_pat

Retrieve personal access token.
format_stats19_ve

Format UK 'Stats19' road traffic casualty data
decode_gl

Decode Google polyline compressed string
format_stats19_ac

Format UK 'Stats19' road traffic casualty data
find_network_nodes

Find graph node ID of closest node to given coordinates
line2df

Convert SpatialLinesDataFrame objects to a data.frame with from and to coords
gtfs2sldf

Import GTFS shapes and route data to SpatialLinesDataFrame.
gclip

Crops spatial object x to the bounding box of spatial object (or matrix) b
line_bearing

Find the bearing of straight lines
islines

Do the intersections between two geometries create lines?
gprojected

Perform GIS functions on a temporary, projected version of a spatial object
gsection

Function to split overlapping SpatialLines into segments
graphhopper_pat

Retrieve personal access token.
line_midpoint

Find the mid-point of lines
is_linepoint

Identify lines that are points
line2route

Convert straight SpatialLinesDataFrame from flow data into routes
line2points

Convert a SpatialLinesDataFrame to points
locate2spdf

Return SpatialPointsDataFrame with located points from OSRM locate service
nearest_cyclestreets

Generate nearest point on the route network of a point using the CycleStreets.net
mapshape

Simplify geometry of spatial objects with the mapshaper library
n_vertices

Retrieve the number of vertices from a SpatialLines or SpatialPolygons object
nearest_osm

Generate nearest point on the route network of a point from OSRM locate service
nearest_google

Generate nearest point on the route network of a point using the Google Maps API
mapshape_available

Does the computer have mapshaper available?
lineLabels

Label SpatialLinesDataFrame objects
nearest2spdf

Return SpatialPointsDataFrame with nearest street from OSRM nearest service
onewaygeo

Aggregate flows so they become non-directional (by geometry - the slow way)
od2odf

Extract coordinates from OD data
od_dist

Quickly calculate Euclidean distances of od pairs
plot,SpatialLinesNetwork,ANY-method

Plot a SpatialLinesNetwork
points2flow

Convert a series of points into geographical flows
onewayid

Aggregate ods so they become non-directional, e.g. by summing travel in both directions.
overline

Convert series of overlapping lines into a route network
od_radiation

Function that estimates flow between points or zones using the radiation model
od2line

Convert flow data to SpatialLinesDataFrame
sum_network_routes

Summarise shortest path between nodes on network
read_table_builder

Import and format Australian Bureau of Statistics (ABS) TableBuilder files
summary,SpatialLinesNetwork-method

Print a summary of a SpatialLinesNetwork
read_stats19_ve

Import and format UK 'Stats19' road traffic casualty data
writeGeoJSON

Write to geojson easily
zones

SpatialPolygonsDataFrame of home locations for flow analysis.
route_graphhopper

Plan a route with the graphhopper routing engine
table2matrix

Return Matrix containing travel times between origins and destinations
route_transportapi_public

Plan a single route with TransportAPI.com
toptail_buff

Clip the beginning and ends SpatialLines to the edge of SpatialPolygon borders
route_cyclestreet

Plan a single route with CycleStreets.net
reproject

Reproject lat/long spatial object so that they are in units of 1m
SpatialLinesNetwork

Create object of class SpatialLinesNetwork from SpatialLinesDataFrame
stplanr-package

stplanr: Sustainable Transport Planning with R
viaroute2sldf

Convert json result of OSRM routing query to SpatialLinesDataFrame
weightfield

Get or set weight field in SpatialLinesNetwork
read_stats19_ac

Import and format UK 'Stats19' road traffic casualty data
read_stats19_ca

Import and format UK 'Stats19' road traffic casualty data
toptail

Clip the first and last n metres of SpatialLines
toptailgs

Clip the first and last n metres of SpatialLines
buff_geo

Create a buffer of n metres for non-projected 'geographical' spatial data
bb2poly

Convert a bounding box to a SpatialPolygonsDataFrame
points2line

Convert a series of points, or a matrix of coordinates, into a line
angle_diff

Calculate the angular difference between lines and a predefined bearing
points2odf

Convert a series of points into a dataframe of origins and destinations
routes_fast

SpatialLinesDataFrame of commuter flows on the travel network
routes_slow

SpatialLinesDataFrame of commuter flows on the travel network
update_line_geometry

Update line geometry
viaroute

Query OSRM service and return json string result
crs_select_aeq

Select a custom projected CRS for the area of interest
cents

SpatialPointsDataFrame of home locations for flow analysis.