Learn R Programming

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

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.

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

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_sf[1:3,] # points representing origins and destinations
#> Simple feature collection with 3 features and 4 fields
#> geometry type:  POINT
#> dimension:      XY
#> bbox:           xmin: -1.546463 ymin: 53.8041 xmax: -1.511861 ymax: 53.81161
#> epsg (SRID):    4326
#> proj4string:    +proj=longlat +datum=WGS84 +no_defs
#>       geo_code  MSOA11NM percent_fem  avslope                   geometry
#> 1708 E02002384 Leeds 055    0.458721 2.856563 POINT (-1.546463 53.80952)
#> 1712 E02002382 Leeds 053    0.438144 2.284782 POINT (-1.511861 53.81161)
#> 1805 E02002393 Leeds 064    0.408759 2.361707  POINT (-1.524205 53.8041)

These datasets can be combined as follows:

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

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

Route functions take lat/lon inputs (results not calculated):

trip <- route_osrm(from = c(-1, 53), to = c(-1.1, 53))

and place names, found using the Google Map API:

We can replicate this call multiple times using line2route, in this case lines 2 to 5. First we’ll create a small subset of the lines:

desire_lines <- travel_network[2:5,]

Next, we’ll calculate the routes (not not evaluated):

routes <- line2route(desire_lines, route_fun = route_osrm)

The resulting routes will look something like this:

routes = routes_fast_sf[2:5, ]
plot(routes$geometry)

Another way to visualise this is with the leaflet package:

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

For more examples, example("line2route").

overline is a function which 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 illustrated below.

routes$All <- desire_lines$All
rnet <- overline2(routes, attrib = "All")
#> Loading required namespace: pbapply
#> 2019-03-20 11:36:35 constructing segments
#> 2019-03-20 11:36:35 transposing 'B to A' to 'A to B'
#> 2019-03-20 11:36:35 removing duplicates
#> 2019-03-20 11:36:35 restructuring attributes
#> 2019-03-20 11:36:35 building geometry
#> 2019-03-20 11:36:35 simplifying geometry
#> 2019-03-20 11:36:35 rejoining segments into linestrings

lwd <- rnet$All / mean(rnet$All)
plot(rnet, lwd = lwd, reset = FALSE)
plot(cents_sf, add = TRUE)

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

splanr depends on rgdal which can be installed on Ubuntu, for example, with:

sudo apt install r-cran-rgdal

To install gdal binaries on other distributions please see here: http://trac.osgeo.org/gdal/wiki/DownloadingGdalBinaries

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

Instructions to install gdal and Quartz are provided at https://github.com/ropensci/geojsonio#install and https://www.xquartz.org/ respectively (Quartz is required for R - as described here).

Funtions, help and contributing

The current list of available functions can be seen on the package’s website at ropensci.github.io/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,388

Version

0.2.8

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Robin Lovelace

Last Published

March 22nd, 2019

Functions in stplanr (0.2.8)

flow_dests

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

Download Stats19 data
flowlines

spatial lines dataset of commuter flows
is_linepoint

Identify lines that are points
islines

Do the intersections between two geometries create lines?
line_length

Calculate length of lines in geographic CRS
line_match

Match two sets of lines based on similarity
od_coords

Create matrices representing origin-destination coordinates
od_coords2line

Convert origin-destination coordinates into desire lines
%>%

Pipe operator
angle_diff

Calculate the angular difference between lines and a predefined bearing
plot,SpatialLinesNetwork,ANY-method

Plot a SpatialLinesNetwork
quadrant

Split a spatial object into quadrants
read_stats19_ac

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

Retrieve personal access token.
calc_moving_catchment

Calculate summary statistics for all features independently.
calc_network_catchment

Calculate catchment area and associated summary statistics using network.
summary,sfNetwork-method

Print a summary of a sfNetwork
format_stats19_ve

Format UK 'Stats19' road traffic casualty data
table2matrix

Return Matrix containing travel times between origins and destinations
as_sf_fun

Convert functions support sf/sp
viaroute2sldf

Convert json result of OSRM routing query to SpatialLinesDataFrame
bbox_scale

Scale a bounding box
calc_catchment

Calculate catchment area and associated summary statistics.
weightfield

Get or set weight field in SpatialLinesNetwork
find_network_nodes

Find graph node ID of closest node to given coordinates
SpatialLinesNetwork-class

An S4 class representing a (typically) transport network
calc_catchment_sum

Calculate summary statistics for catchment area.
flow

data frame of commuter flows
lineLabels

Label SpatialLinesDataFrame objects
line_bearing

Find the bearing of straight lines
gclip

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

Function to split overlapping SpatialLines into segments
SpatialLinesNetwork

Create object of class SpatialLinesNetwork or sfNetwork
cents

Spatial points representing home locations
gtfs2sldf

Import GTFS shapes and route data to SpatialLinesDataFrame.
line_midpoint

Find the mid-point of lines
mapshape

Simplify geometry of spatial objects with the mapshaper library
mapshape_available

Does the computer have mapshaper available?
decode_gl

Decode Google polyline compressed string
crs_select_aeq

Select a custom projected CRS for the area of interest
line_sample

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

example destinations data
geo_buffer

Perform a buffer operation on a temporary projected CRS
line_via

Add geometry columns representing a route via intermediary points
locate2spdf

Return SpatialPointsDataFrame with located points from OSRM locate service
format_stats19_ac

Format UK 'Stats19' road traffic casualty data
format_stats19_ca

Format UK 'Stats19' road traffic casualty data
points2line

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

Flexible function to generate bounding boxes
points2odf

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

Quickly calculate Euclidean distances of od pairs
route_dodgr

Route on local data using the dodgr package
geo_code

Convert text strings into points on the map
route_graphhopper

Plan a route with the graphhopper routing engine
l_poly

Line polygon
geo_length

Calculate line length of line with geographic or projected CRS
geo_bb_matrix

Create matrix representing the spatial bounds of an object
line2df

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

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

Plan a route with OSRM
nearest_google

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

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

Generate ordered ids of OD pairs so lowest is always first
onewayid

Aggregate ods so they become non-directional
line_segment

Divide SpatialLines dataset into regular segments
line_to_points

Convert a SpatialLinesDataFrame to points The number of points will be double the number of lines with line2points. A closely related function, line2pointsn returns all the points that were line vertices. The points corresponding with a given line, i, will be (2*i):((2*i)+1).
n_vertices

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

Return SpatialPointsDataFrame with nearest street from OSRM nearest service
route_transportapi_public

Plan a single route with TransportAPI.com
nearest_osm

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

Example of OpenStreetMap road network
toptail_buff

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

Extract coordinates from OD data
geo_select_aeq

Select a custom projected CRS for the area of interest
toptailgs

Clip the first and last n metres of SpatialLines
sp_aggregate

Aggregate SpatialPolygonsDataFrame to new geometry.
geo_toptail

Clip the first and last n metres of SpatialLines
stplanr-deprecated

Deprecated functions in stplanr
update_line_geometry

Update line geometry
od2line

Convert flow data to SpatialLinesDataFrame
od_aggregate

Aggregate OD data between polygon geometries
line2route

Convert straight OD data (desire lines) into routes
read_stats19_ca

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

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

Convert straight SpatialLinesDataFrame from flow data into routes retrying on connection (or other) intermittent failures
routes_fast

spatial lines dataset of commuter flows on the travel network
mats2line

Convert 2 matrices to lines
viaroute

Query OSRM service and return json string result
routes_slow

spatial lines dataset of commuter flows on the travel network
writeGeoJSON

Write to geojson easily
zones

Spatial polygons of home locations for flow analysis.
overline

Convert series of overlapping lines into a route network
overline2

Overlay duplicated lines
n_sample_length

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

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

Aggregate flows so they become non-directional (by geometry - the slow way)
plot,sfNetwork,ANY-method

Plot an sfNetwork
read_table_builder

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

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

Convert a series of points into geographical flows
route_local

Plan a route with local data
sum_network_routes

Summarise shortest path between nodes on network
route_network

spatial lines dataset representing a route network
route

Plan routes on the transport network
summary,SpatialLinesNetwork-method

Print a summary of a SpatialLinesNetwork
route_cyclestreet

Plan a single route with CycleStreets.net
sfNetwork-class

An S4 class representing a (typically) transport network
sln2points

Generate spatial points representing nodes on a SpatialLinesNetwork or sfNetwork.
stplanr-package

stplanr: Sustainable Transport Planning with R
sum_network_links

Summarise links from shortest paths data
buff_geo

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

SpatialPointsDataFrame representing road traffic deaths
dist_google

Return travel network distances and time using the Google Maps API