Learn R Programming

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

stplanr

stplanr is a package for sustainable transport planning with R.

It provides functions for solving common problems in transport planning and modelling, such as how to best get from point A to point B. The overall aim is to provide a reproducible, transparent and accessible toolkit to help people better understand transport systems and inform policy, as outlined in a paper about the package, and the potential for open source software in transport planning in general, published in the R Journal.

The initial work on the project was funded by the Department of Transport (DfT) as part of the development of the Propensity to Cycle Tool (PCT), a web application to explore current travel patterns and cycling potential at zone, desire line, route and route network levels (see www.pct.bike and click on a region to try it out). The basis of the methods underlying the PCT is origin-destination data, which are used to highlight where many short distance trips are being made, and estimate how many could switch to cycling. The results help identify where cycleways are most needed, an important component of sustainable transport planning infrastructure engineering and policy design.

See the package vignette (e.g. via vignette("introducing-stplanr")) or an academic paper on the Propensity to Cycle Tool (PCT) for more information on how it can be used. This README provides some basics.

Much of the work supports research undertaken at the Leeds’ Institute for Transport Studies (ITS) but stplanr should be useful to transport researchers and practitioners needing free, open and reproducible methods for working with geographic data everywhere.

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. stplanr facilitates this with od2line(), which takes flow and geographical data as inputs and outputs spatial data. Some example data is provided in the package:

library(stplanr)

Let’s take a look at this data:

od_data_sample[1:3, 1:3] # typical form of flow data
#> # A tibble: 3 x 3
#>   geo_code1 geo_code2   all
#>   <chr>     <chr>     <dbl>
#> 1 E02002361 E02002361   109
#> 2 E02002361 E02002363    38
#> 3 E02002361 E02002367    10
cents_sf[1:3,] # points representing origins and destinations
#>       geo_code  MSOA11NM percent_fem  avslope             geometry
#> 1708 E02002384 Leeds 055    0.458721 2.856563 -1.546463, 53.809517
#> 1712 E02002382 Leeds 053    0.438144 2.284782 -1.511861, 53.811611
#> 1805 E02002393 Leeds 064    0.408759 2.361707 -1.524205, 53.804098

These datasets can be combined as follows:

travel_network <- od2line(flow = od_data_sample, zones = cents_sf)
w <- flow$all / max(flow$all) *10
plot(travel_network, lwd = w)

stplanr has many functions for working with OD data. See the stplanr-od vignette for details.

The package can also allocate flows to the road network, e.g. with CycleStreets.net and the OpenStreetMap Routing Machine (OSRM) API interfaces. These are supported in route_*() functions such as route_cyclestreets and route_osrm():

Routing can be done using a range of back-ends and using lat/lon or desire line inputs with the route() function, as illustrated by the following commands which calculates the route between Fleet Street and Southwark Street over the River Thames on Blackfriars Bridge in London:

library(osrm)
#> Data: (c) OpenStreetMap contributors, ODbL 1.0 - http://www.openstreetmap.org/copyright
#> Routing: OSRM - http://project-osrm.org/
trip <- route(
  from = c(-0.11, 51.514),
  to = c(-0.10, 51.506),
  route_fun = osrmRoute,
  returnclass = "sf"
  )
#> Most common output is sf
mapview::mapview(trip)

You can also use and place names, found using the Google Map API:

trip2 <- route(
  from = "Leeds",
  to = "Bradford",
  route_fun = osrmRoute,
  returnclass = "sf"
  )
#> Most common output is sf
mapview::mapview(trip2)

We can replicate this call multiple times with the l argument in route():

desire_lines <- travel_network[2:6, ]

Next, we’ll calculate the routes:

routes <- route(
  l = desire_lines,
  route_fun = osrmRoute,
  returnclass = "sf"
  )
mapview::mapview(routes) +
  mapview::mapview(desire_lines, color = "red")

For more examples, example("route").

overline() takes a series of route-allocated lines, splits them into unique segments and aggregates the values of overlapping lines. This can represent where there will be most traffic on the transport system, as demonstrated in the following code chunk.

routes$foot <- desire_lines$foot
rnet <- overline(routes, attrib = "foot")
#> 2020-09-03 22:24:08 constructing segments
#> 2020-09-03 22:24:08 building geometry
#> 2020-09-03 22:24:08 simplifying geometry
#> 2020-09-03 22:24:08 aggregating flows
#> 2020-09-03 22:24:08 rejoining segments into linestrings

The resulting route network, with segment totals calculated from overlapping parts for the routes for walking, can be visualised as follows:

plot(rnet["foot"], lwd = rnet$foot)

The above plot represents the number walking trips made (the ‘flow’) along particular segments of a transport network.

Policy applications

The examples shown above, based on tiny demonstration datasets, may not seem particularly revolutionary. At the city scale, however, this type of analysis can be used to inform sustainable transport policies, as described in papers describing the Propensity to Cycle Tool (PCT), and its application to calculate cycling to school potential across England.

Results generated by stplanr are now part of national government policy: the PCT is the recommended tool for local and regional authorities developing strategic cycle network under the Cycling and Walking Infrastructure Strategy (CWIS), which is part of the Infrastructure Act 2015. stplanr is helping dozens of local authorities across the UK to answer the question: where to prioritise investment in cycling? In essence, stplanr was designed to support sustainable transport policies.

There are many other research and policy questions that functions in stplanr, and other open source software libraries and packages, can help answer. At a time of climate, health and social crises, it is important that technology is not only sustainable itself (e.g. as enabled by open source communities and licenses) but that it contributes to a sustainable future.

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 stplanr on Linux and Mac

stplanr depends on sf. Installation instructions for Mac, Ubuntu and other Linux distros can be found here: https://github.com/r-spatial/sf#installing

Functions, help and contributing

The current list of available functions can be seen on the package’s website at docs.ropensci.org/stplanr/, or with the following command:

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

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

?od2line

To contribute, report bugs or request features, see the issue tracker.

Further resources / tutorials

Want to learn how to use open source software for reproducible sustainable transport planning work? Now is a great time to learn. Transport planning is a relatively new field of application in R. However, there are already some good resources on the topic, including (any further suggestions: welcome):

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.8.2

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Last Published

April 6th, 2021

Functions in stplanr (0.8.2)

as_sf_fun

Convert functions support sf/sp
angle_diff

Calculate the angular difference between lines and a predefined bearing
SpatialLinesNetwork

Create object of class SpatialLinesNetwork or sfNetwork
ca_local

SpatialPointsDataFrame representing road traffic deaths
bbox_scale

Scale a bounding box
calc_catchment

Calculate catchment area and associated summary statistics.
SpatialLinesNetwork-class

An S4 class representing a (typically) transport network
calc_catchment_sum

Calculate summary statistics for catchment area.
calc_moving_catchment

Calculate summary statistics for all features independently.
api_pat

Retrieve personal access token.
flow_dests

data frame of invented commuter flows with destinations in a different layer than the origins
geo_toptail

Clip the first and last n metres of SpatialLines
calc_network_catchment

Calculate catchment area and associated summary statistics using network.
gsection

Function to split overlapping SpatialLines into segments
cents

Spatial points representing home locations
gclip

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

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

Select a custom projected CRS for the area of interest
geo_bb

Flexible function to generate bounding boxes
destination_zones

Example destinations data
find_network_nodes

Find graph node ID of closest node to given coordinates
dist_google

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

Calculate length of lines in geographic CRS
is_linepoint

Identify lines that are points
islines

Do the intersections between two geometries create lines?
line_match

Match two sets of lines based on similarity
geo_code

Convert text strings into points on the map
geo_length

Calculate line length of line with geographic or projected CRS
flow

data frame of commuter flows
line_bearing

Find the bearing of straight lines
flowlines

spatial lines dataset of commuter flows
l_poly

Line polygon
geo_bb_matrix

Create matrix representing the spatial bounds of an object
od_aggregate_from

Summary statistics of trips originating from zones in OD data
n_sample_length

Sample integer number from given continuous vector of line lengths and probabilities, with total n
mats2line

Convert 2 matrices to lines
od2odf

Extract coordinates from OD data
od_aggregate_to

Summary statistics of trips arriving at destination zones in OD data
line2df

Convert geographic line objects to a data.frame with from and to coords
od_coords

Create matrices representing origin-destination coordinates
line2points

Convert a spatial (linestring) object to points
line2route

Convert straight OD data (desire lines) into routes
line_segment

Divide SpatialLines dataset into regular segments
line2routeRetry

Convert straight spatial (linestring) object from flow data into routes retrying on connection (or other) intermittent failures
geo_buffer

Perform a buffer operation on a temporary projected CRS
od_coords2line

Convert origin-destination coordinates into desire lines
line_via

Add geometry columns representing a route via intermediary points
overline_intersection

Convert series of overlapping lines into a route network
overline

Convert series of overlapping lines into a route network
od_data_lines

Example of desire line representations of origin-destination data from UK Census
route

Plan routes on the transport network
od_id_order

Generate ordered ids of OD pairs so lowest is always first This function is slow on large datasets, see szudzik_pairing for faster alternative
od_oneway

Aggregate od pairs they become non-directional
lineLabels

Label SpatialLinesDataFrame objects
route_average_gradient

Return average gradient across a route
line_breakup

Break up line objects into shorter segments
line_midpoint

Find the mid-point of lines
od_data_sample

Example of origin-destination data from UK Census
line_sample

Sample n points along lines with density proportional to a weight
route_local

Plan a route with local data
od_data_routes

Example segment-level route data
od_id

Combine two ID values to create a single ID number
od_dist

Quickly calculate Euclidean distances of od pairs
n_vertices

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

Import and format Australian Bureau of Statistics (ABS) TableBuilder files
route_nearest_point

Find nearest route to a given point
reproject

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

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

Convert a series of points into geographical flows
mapshape

Simplify geometry of spatial objects with the mapshaper library
rnet_get_nodes

Extract nodes from route network
sum_network_routes

Summarise shortest path between nodes on network
nearest_cyclestreets

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

Assign segments in a route network to groups
points2odf

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

spatial lines dataset representing a route network
summary,SpatialLinesNetwork-method

Print a summary of a SpatialLinesNetwork
mapshape_available

Does the computer have mapshaper available?
od2line

Convert origin-destination data to spatial lines
nearest_google

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

Get or set weight field in SpatialLinesNetwork
od_to_odmatrix

Convert origin-destination data from long to wide format
onewaygeo

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

Example of OpenStreetMap road network
route_osrm

Plan routes on the transport network using the OSRM server
plot,SpatialLinesNetwork,ANY-method

Plot a SpatialLinesNetwork
writeGeoJSON

Write to geojson easily
route_slope_vector

Calculate the gradient of line segments from distance and elevation vectors
quadrant

Split a spatial object into quadrants
route_slope_matrix

Calculate the gradient of line segments from a matrix of coordinates
odmatrix_to_od

Convert origin-destination data from wide to long format
route_dodgr

Route on local data using the dodgr package
route_transportapi_public

Plan a single route with TransportAPI.com
route_google

Find shortest path using Google services
route_split

Split route in two at point on or near network
rnet_breakup_vertices

Break up an sf object with LINESTRING geometry.
route_rolling_average

Return smoothed averages of vector
route_rolling_diff

Return smoothed differences between vector values
route_split_id

Split route based on the id or coordinates of one of its vertices
rnet_cycleway_intersection

Example of cycleway intersection data showing problems for SpatialLinesNetwork objects
overline_spatial

Spatial aggregation of routes represented with sp classes
stplanr-package

stplanr: Sustainable Transport Planning with R
routes_fast

spatial lines dataset of commuter flows on the travel network
plot,sfNetwork,ANY-method

Plot an sfNetwork
rnet_roundabout

Example of roundabout data showing problems for SpatialLinesNetwork objects
sfNetwork-class

An S4 class representing a (typically) transport network
stplanr-deprecated

Deprecated functions in stplanr
sln_clean_graph

Clean spatial network - return an sln with a single connected graph
sln2points

Generate spatial points representing nodes on a SpatialLinesNetwork or sfNetwork.
sln_add_node

Add node to spatial lines object
routes_slow

spatial lines dataset of commuter flows on the travel network
rnet_add_node

Add a node to route network
toptailgs

Clip the first and last n metres of SpatialLines
rnet_overpass

Example of overpass data showing problems for SpatialLinesNetwork objects
%>%

Pipe operator
rnet_boundary_points

Get points at the beginner and end of linestrings
sum_network_links

Summarise links from shortest paths data
update_line_geometry

Update line geometry
route_cyclestreets

Plan a single route with CycleStreets.net
route_sequential_dist

Calculate the sequential distances between sequential coordinate pairs
toptail_buff

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

Get a route from the BikeCitizens web service
summary,sfNetwork-method

Print a summary of a sfNetwork
zones

Spatial polygons of home locations for flow analysis.
route_rolling_gradient

Calculate rolling average gradient from elevation data at segment level