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.

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). The PCT uses origin-destination data as the basis of spatial analysis and modelling work to identify where bicycle paths are most needed. 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 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. 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)
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, 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:

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.

intrazone <- travel_network$Area.of.residence == travel_network$Area.of.workplace
travel_network <- travel_network[!intrazone,]
t_routes <- line2route(travel_network, route_fun = route_osrm)
plot(t_routes)

Another way to visualise this is with the leaflet package:

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 segments and aggregates the values of overlapping lines. This can represent where there will be most traffic on the transport system, as illustrated below.

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

lwd <- rnet$All / mean(rnet$All)
plot(rnet, lwd = lwd)
points(cents)

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

Dependencies

stplanr imports many great packages that it depends on. Many thanks to the developers of these tools:

desc = read.dcf("DESCRIPTION")
headings = dimnames(desc)[[2]]
fields = which(headings %in% c("Depends", "Imports", "Suggests"))
pkgs = paste(desc[fields], collapse = ", ")
pkgs = gsub("\n", " ", pkgs)
strsplit(pkgs, ",")[[1]]
#>  [1] "sp"                " R (>= 3.0)"       " curl"            
#>  [4] " readr"            " dplyr"            " httr"            
#>  [7] " jsonlite"         " stringi"          " stringr"         
#> [10] " lubridate"        " maptools"         " raster"          
#> [13] " rgdal"            " rgeos"            " openxlsx"        
#> [16] " methods"          " R.utils"          " geosphere"       
#> [19] " Rcpp (>= 0.12.1)" " igraph"           " nabor"           
#> [22] " rlang"            " sf"               " testthat"        
#> [25] " knitr"            " rmarkdown"        " dodgr"

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

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Robin Lovelace

Last Published

May 19th, 2018

Functions in stplanr (0.2.4)

geo_projected

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

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

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

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

Create object of class SpatialLinesNetwork or sfNetwork
is_linepoint

Identify lines that are points
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).
format_stats19_ca

Format UK 'Stats19' road traffic casualty data
islines

Do the intersections between two geometries create lines?
mapshape

Simplify geometry of spatial objects with the mapshaper library
format_stats19_ac

Format UK 'Stats19' road traffic casualty data
locate2spdf

Return SpatialPointsDataFrame with located points from OSRM locate service
line_segment

Divide SpatialLines dataset into regular segments
od_coords

General function to create a matrix representing origins and destinations
calc_moving_catchment

Calculate summary statistics for all features independently.
ca_local

SpatialPointsDataFrame representing road traffic deaths
od_radiation

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

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

Line polygon
read_stats19_ve

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

Calculate length of lines in geographic CRS
od_dist

Quickly calculate Euclidean distances of od pairs
points2odf

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

Match two sets of lines based on similarity
%>%

Pipe operator
read_stats19_ac

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

Convert series of overlapping lines into a route network
read_stats19_ca

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

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

Plan a single route with TransportAPI.com
cents

Spatial points representing home locations
route_network

spatial lines dataset representing a route network
calc_network_catchment

Calculate catchment area and associated summary statistics using network.
route_osrm

Plan a route with OSRM
dist_google

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

Calculate summary statistics for catchment area.
crs_select_aeq

Select a custom projected CRS for the area of interest
gsection

Function to split overlapping SpatialLines into segments
sln2points

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

spatial lines dataset of commuter flows on the travel network
dl_stats19

Download Stats19 data
sp_aggregate

Aggregate SpatialPolygonsDataFrame to new geometry.
reproject

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

Split a spatial object into quadrants
route

Plan routes on the transport network
sum_network_routes

Summarise shortest path between nodes on network
summary,SpatialLinesNetwork-method

Print a summary of a SpatialLinesNetwork
viaroute2sldf

Convert json result of OSRM routing query to SpatialLinesDataFrame
summary,sfNetwork-method

Print a summary of a sfNetwork
gtfs2sldf

Import GTFS shapes and route data to SpatialLinesDataFrame.
geo_bb

Flexible function to generate bounding boxes
geo_buffer

Perform a buffer operation on a temporary projected CRS
line2route

Convert straight OD data (desire lines) into routes
geo_code

Convert text strings into points on the map
lineLabels

Label SpatialLinesDataFrame objects
weightfield

Get or set weight field in SpatialLinesNetwork
line_bearing

Find the bearing of straight lines
line2routeRetry

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

Plan a single route with CycleStreets.net
nearest2spdf

Return SpatialPointsDataFrame with nearest street from OSRM nearest service
n_vertices

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

Return Matrix containing travel times between origins and destinations
nearest_osm

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

Convert flow data to SpatialLinesDataFrame
update_line_geometry

Update line geometry
od2odf

Extract coordinates from OD data
viaroute

Query OSRM service and return json string result
route_graphhopper

Plan a route with the graphhopper routing engine
toptail_buff

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

Create matrix representing the spatial bounds of an object
toptailgs

Clip the first and last n metres of SpatialLines
points2flow

Convert a series of points into geographical flows
geo_toptail

Clip the first and last n metres of SpatialLines
od_aggregate

Aggregate OD data between polygon geometries
sfNetwork-class

An S4 class representing a (typically) transport network
writeGeoJSON

Write to geojson easily
points2line

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

Select a custom projected CRS for the area of interest
routes_slow

spatial lines dataset of commuter flows on the travel network
zones

Spatial polygons of home locations for flow analysis.
line_midpoint

Find the mid-point of lines
line_sample

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

Does the computer have mapshaper available?
onewaygeo

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

Sample integer number from given continuous vector of line lengths and probabilities, with total n
plot,SpatialLinesNetwork,ANY-method

Plot a SpatialLinesNetwork
onewayid

Aggregate ods so they become non-directional
plot,sfNetwork,ANY-method

Plot an sfNetwork
sum_network_links

Summarise links from shortest paths data
stplanr-package

stplanr: Sustainable Transport Planning with R
as_sf_fun

Convert functions support sf/sp
angle_diff

Calculate the angular difference between lines and a predefined bearing
SpatialLinesNetwork-class

An S4 class representing a (typically) transport network
api_pat

Retrieve personal access token.
format_stats19_ve

Format UK 'Stats19' road traffic casualty data
gclip

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

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

Scale a bounding box
geo_length

Calculate line length of line with geographic or projected CRS
calc_catchment

Calculate catchment area and associated summary statistics.
decode_gl

Decode Google polyline compressed string
destination_zones

example destinations data
find_network_nodes

Find graph node ID of closest node to given coordinates
flow

data frame of commuter flows
flow_dests

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

spatial lines dataset of commuter flows