Package 'arear'

Title: Geospatial Convenience Functions and a Supply Demand Catchment Area Generator
Description: Geospatial function collection from the COVID-19 pandemic. The main focus of this was integrating geospatial demographic, hospital capacity and COVID data from England, Scotland, Wales and Northern Ireland, all of which were available on different sites and methods. The UK has a wide range of administrative geographic boundaries for different purposes and moving from different scales and resolutions proved necessary. As the geospatial operations are quite time consuming but don't need to be repeated the ability to cache results of geospatial transformations is useful and embedded into these functions.
Authors: Robert Challen [aut, cre] (ORCID: <https://orcid.org/0000-0002-5504-7768>)
Maintainer: Robert Challen <[email protected]>
License: MIT + file LICENSE
Version: 0.4.0
Built: 2026-05-18 08:35:27 UTC
Source: https://github.com/terminological/arear

Help Index


NHS trust admissions data from the legacy COVID API from 2021

Description

NHS trust admissions data from the legacy COVID API from 2021

Usage

apiTrusts

Format

A 72928 line data frame:

date

the ONS code for the ares

area_name

The name for the area

area_type

the type of area (LSOA, DZ or LGD)

area_code

the NHS ODS code

metric

hospital cases

metric_name

hospital cases

value

the count


Get feature service information from an arcgis rest service

Description

Get feature service information from an arcgis rest service

Usage

arcgisServiceInfo(url, ...)

Arguments

url

the base rest service url

...

Named arguments passed on to .cache_download

.nocache

if set to TRUE all caching is disabled

.cache

the location of the downloaded files

.stale

how long to leave this file before replacing it.

.extn

the file name extension

Value

a dataframe of available feature and map services

Examples

url = "https://services1.arcgis.com/ESMARspQHYMw9BZ9/ArcGIS/rest/services"
arcgisServiceInfo(url)

Clear data from the passthrough cache for complex or long running operations

Description

Clear data from the passthrough cache for complex or long running operations

Usage

cache_clear(
  .cache = rappdirs::user_cache_dir(utils::packageName()),
  .prefix = ".*",
  interactive = TRUE
)

Arguments

.cache

the location of the cache as a directory. May get its value from options("ggrrr.cache.dir") or the default value of rappdirs::user_cache_dir("ggrrr")

.prefix

a regular expression matching the prefix of the cached item, so that do selective clean up operations. defaults to everything.

interactive

suppress 'are you sure?' warning with a FALSE value (defaults to TRUE)

Value

nothing. called for side effects


Create and cache a catchment area map

Description

This implements the label propagation algorithm described in our paper: R. J. Challen, G. J. Griffith, L. Lacasa, and K. Tsaneva-Atanasova, ‘Algorithmic hospital catchment area estimation using label propagation’, BMC Health Services Research, vol. 22, no. 1, p. 828, June 2022, doi: 10.1186/s12913-022-08127-7.

Usage

catchment(
  supplyShape,
  supplyIdVar = "code",
  supplyVar,
  supplyOutputVars = supplyShape %>% dplyr::groups(),
  demandShape,
  demandIdVar = "code",
  demandVar,
  growthConstant = 1.2,
  bridges = arear::ukconnections,
  outputMap = TRUE,
  ...
)

Arguments

supplyShape

a sf object containing a list of the locations of supply points, with a column containing supply capacity, for example NHS hospital sites, with a bed capacity count

supplyIdVar

the variable name of the identifier of the supplier or group of suppliers. For example this could be an NHS trust (multiple sites)

supplyVar

the column name of the supply parameter. This could be number of beds in a hospital.

supplyOutputVars

(optional - defaults to grouping) the columns from the input that are to be retained in the output

demandShape

the sf object with the geographical map of the demand surface. For example the geographical distribution of the population served,

demandIdVar

the column name of the unique identifier of the areas,

demandVar

the column name of the demand parameter. This could be the population in each region

growthConstant

a growth parameter which defines how quickly each label propagates

bridges

a named list containing extra linkages beyond those inferred by the demandShape topology. These are used to add in bridges

outputMap

should we export a shape file or just the mapping file

...

Named arguments passed on to .cached

.nocache

an option to defeat the caching which can be set globally as options("cache.disable"=TRUE)

.stale

the length of time in days to keep cached data before considering it as stale. can also be set by options("cache.stale")

Value

a


Create a catchment area map

Description

This implements the label propagation algorithm described in our paper: R. J. Challen, G. J. Griffith, L. Lacasa, and K. Tsaneva-Atanasova, ‘Algorithmic hospital catchment area estimation using label propagation’, BMC Health Services Research, vol. 22, no. 1, p. 828, June 2022, doi: 10.1186/s12913-022-08127-7.

Usage

createCatchment(
  supplyShape,
  supplyIdVar = "code",
  supplyVar,
  supplyOutputVars = supplyShape %>% dplyr::groups(),
  demandShape,
  demandIdVar = "code",
  demandVar,
  growthConstant = 1.2,
  bridges = arear::ukconnections,
  outputMap = TRUE
)

Arguments

supplyShape

a sf object containing a list of the locations of supply points, with a column containing supply capacity, for example NHS hospital sites, with a bed capacity count

supplyIdVar

the variable name of the identifier of the supplier or group of suppliers. For example this could be an NHS trust (multiple sites)

supplyVar

the column name of the supply parameter. This could be number of beds in a hospital.

supplyOutputVars

(optional - defaults to grouping) the columns from the input that are to be retained in the output

demandShape

the sf object with the geographical map of the demand surface. For example the geographical distribution of the population served,

demandIdVar

the column name of the unique identifier of the areas,

demandVar

the column name of the demand parameter. This could be the population in each region

growthConstant

a growth parameter which defines how quickly each label propagates

bridges

a named list containing extra linkages beyond those inferred by the demandShape topology. These are used to add in bridges

outputMap

should we export a shape file or just the mapping file

Value

a


Create a neighbourhood network from touching regions in a map

Description

A network of neighbouring map regions including connections due to bridges airports or ferry links, defined in the bridges input.

Usage

createNeighbourNetwork(
  shape,
  idVar = "code",
  bridges = arear::ukconnections,
  queen = FALSE,
  ...
)

Arguments

shape

a 'sf' object

idVar

the column containing the coded identifier of the map

bridges

a df with the following columns: 'name' 'start.lat' 'start.long' 'end.lat' 'end.long' defining connections between non touching shapes (e.g. bridges / ferries / etc.)

queen

- include neighbouring areas that only touch at corners, defaults to false.

...

Named arguments passed on to .cached

.nocache

an option to defeat the caching which can be set globally as options("cache.disable"=TRUE)

.stale

the length of time in days to keep cached data before considering it as stale. can also be set by options("cache.stale")

Value

an edge list of ids with from and to columns

Examples

edges = createNeighbourNetwork(
  shape = arear::testdata$grid11x11,
  idVar = "id"
)

# in regular grid each cell has 4 neighbours except the edges and corners
# we loose 1 per edge

nrow(edges) == 11*11*4-4*11

queens = createNeighbourNetwork(
  shape = arear::testdata$grid11x11,
  idVar = "id",
  queen = TRUE
)

# each cell has 8 queen neighbours
# except edge pieces which have 3 less, and corners which have 5 less.
nrow(queens) == 11*11*8 - 4*9*3 - 4*5

Download a geojson url, optionally simplifies and cache the result

Description

Download a geojson url, optionally simplifies and cache the result

Usage

downloadGeojson(geojsonUrl, simplify = FALSE, ...)

Arguments

geojsonUrl

the URL of the geojson resource or ESRI feature service layer

simplify

do you want to simplify the map

...

Named arguments passed on to featureServerLayerQuery

where

an SQL query (defaults to whole map)

select

the columns to return (see featureServerLayerInfo())

limit

maximum rows to return

crs

the coordinate reference system

queryParams

additional query parameters passed to the request to the feature server

...

Named arguments passed on to .cache_post

body

a named list of POST data

as

how the response is delivered?

Named arguments passed on to .cached

.nocache

an option to defeat the caching which can be set globally as options("cache.disable"=TRUE)

.stale

the length of time in days to keep cached data before considering it as stale. can also be set by options("cache.stale")

Value

the 'sf' object for this geoJson

Examples

# The ONS UK country files:
if (interactive()) {
  svc = "https://services1.arcgis.com/ESMARspQHYMw9BZ9/ArcGIS/rest/services"
  fs = sprintf("%s/%s",svc,"Countries_December_2024_Boundaries_UK_BUC/FeatureServer")
  layer = sprintf("%s/%s",fs,"0")
  map = downloadGeojson(layer)
  map %>% dplyr::glimpse()
}

Download a shape file map

Description

This function downloads and caches a zipped shape file map, unpacks it, finds the correct shape file layer optionally simplifies it and converts it to 'sf'.

Usage

downloadMap(zipUrl, mapName = NULL, simplify = FALSE, ...)

Arguments

zipUrl

the URL of the zipped shape file

mapName

(optional) the layer name or map name - this is '"xyz"' if a zip file contains '"xyz.shp"'. Usually there is one '.shp' file in a zip file, and by default it will be picked if this is not set.

simplify

do you want to simplify the map?

...

Named arguments passed on to .cached

.nocache

an option to defeat the caching which can be set globally as options("cache.disable"=TRUE)

.stale

the length of time in days to keep cached data before considering it as stale. can also be set by options("cache.stale")

Value

a 'sf' object containing the map

Examples

## Not run: 
downloadMap(
  zipUrl="https://bit.ly/3A9TnR1"
)

## End(Not run)

Get layer information from a feature service

Description

Get layer information from a feature service

Usage

featureServerInfo(url, ...)

Arguments

url

the feature service url

...

Named arguments passed on to .cache_download

.nocache

if set to TRUE all caching is disabled

.cache

the location of the downloaded files

.stale

how long to leave this file before replacing it.

.extn

the file name extension

Value

a dataframe of layers

Examples

svc = "https://services1.arcgis.com/ESMARspQHYMw9BZ9/ArcGIS/rest/services"
fs = sprintf("%s/%s",svc,"Countries_December_2024_Boundaries_UK_BUC/FeatureServer")
url = sprintf("%s/%s",fs,"0")
featureServerInfo(fs)

Get field information from a feature service layer.

Description

Get field information from a feature service layer.

Usage

featureServerLayerInfo(url, ...)

Arguments

url

the feature service layer url. If no layer is specified the first one is selected.

...

Named arguments passed on to .cache_download

.nocache

if set to TRUE all caching is disabled

.cache

the location of the downloaded files

.stale

how long to leave this file before replacing it.

.extn

the file name extension

Value

a dataframe of field names for the selected layer

Examples

svc = "https://services1.arcgis.com/ESMARspQHYMw9BZ9/ArcGIS/rest/services"
fs = sprintf("%s/%s",svc,"Countries_December_2024_Boundaries_UK_BUC/FeatureServer")
layer = sprintf("%s/%s",fs,"0")
featureServerLayerInfo(layer)

Execute and cache a query on a Feature Server

Description

Allow basic filtering queries only at the moment. Will cache the results and handles multipart transfers.

Usage

featureServerLayerQuery(
  url,
  where = "1 = 1",
  select = "*",
  ...,
  limit = NULL,
  crs = 4326,
  queryParams = list()
)

Arguments

url

the URL of the feature service layer (if layer is not known the first feature layer will be used)

where

an SQL query (defaults to whole map)

select

the columns to return (see featureServerLayerInfo())

...

Named arguments passed on to .cache_post

body

a named list of POST data

as

how the response is delivered?

limit

maximum rows to return

crs

the coordinate reference system

queryParams

additional query parameters passed to the request to the feature server

Value

a 'sf' of the query result

Examples

svc = "https://services1.arcgis.com/ESMARspQHYMw9BZ9/ArcGIS/rest/services"
fs = sprintf("%s/%s",svc,"Countries_December_2024_Boundaries_UK_BUC/FeatureServer")
layer = sprintf("%s/%s",fs,"0")

# default all 4 nations:
sf = featureServerLayerQuery(layer)
cat(sf$CTRY24CD)

# england only
sf2 = featureServerLayerQuery(layer, where="CTRY24CD LIKE 'E%'")
cat(sf2$CTRY24CD)

if (interactive()) {
  # Download the first 4000 LSOAs. There are lots of LSOAs and this
  # query has to be paginated. This also shows the limit feature
  # and the verbose output of the cache.
  lsoa = sprintf("%s/%s",svc,"LSOA_DEC_2021_EW_NC_v3/FeatureServer/0")
  withr::with_options(list(cache.verbose=TRUE), {
    sf_lsoa = featureServerLayerQuery(lsoa, limit = 4000)
  })

  cat(nrow(sf_lsoa))
}

Generate a mapping table between 2 'sf' dataframes.

Description

This assumes unique keys defined in input and output shapes through column grouping and outputs a mapping table between input and output groups. The input is related to the output by containment. I.e. the result will be where the input is wholly contained within the output shape

Usage

getContainedIn(
  inputShape,
  outputShape,
  inputVars = inputShape %>% dplyr::groups(),
  outputVars = outputShape %>% dplyr::groups(),
  suffix = c(".x", ".y")
)

Arguments

inputShape

- a sf containing points of interest (or shapes)

outputShape

- a sf containing polygons to locate the input in.

inputVars

- defines the columns of the input that you want to retain (as a dplyr::vars(...) list). This grouping should uniquely identify the row. If not present will use the current grouping of inputShape.

outputVars

- defines the columns of the output that you want to retain (as a dplyr::vars(...) list). This grouping should uniquely identify the row. If not present will use the current grouping of outputShape.

suffix

- the suffix of any duplicated columns as per dplyr::inner_join()

Value

- a mapping as a dataframe relating the 'inputVars' columns and 'outputVars' columns

Examples

# find the hospitals in a given area.
mapping = getContainedIn(
  inputShape = arear::surgecapacity,
  outputShape = arear::ukcovidmap(),
  inputVars = dplyr::vars(hospitalId),
  outputVars = dplyr::vars(code)
)

Intersection of 2 shapes

Description

get the intersection between to maps with ids. Caches the result in the working directory.

Usage

getIntersection(
  inputShape,
  outputShape,
  suffix = c(".x", ".y"),
  recalcArea = TRUE,
  ...
)

Arguments

inputShape

- the input sf

outputShape

- the output sf

suffix

- the suffix of any duplicated columns as per dplyr::inner_join()

recalcArea

- do you need the area of the intersected shape (e.g. for areal interpolation)

...

passed on to .cached() (cache control) - relevant is nocache = TRUE which prevents this from being precalculated

Value

a sf object representing the intersection of the input and output shapes.


Gets maps for which the metadata is known.

Description

If a map needs to be downloaded as a shapefile then it is stored temporarily. The location of this download directory can be set as option("arear.download.dir" = "~/.)

Usage

getMap(mapId = names(sources)[1], sources = arear::mapsources, ...)

Arguments

mapId

either: a name of a default map

sources

or: a named list of map sources. Each map source entry must be a named list containing the following information:

- 'url': the download URL of the map - 'mapName': either 'geojson' or for shapes the layer name containing the map. if not given the first shape file layer will be used. - 'simplify' (opt: boolean) do you want the map to be simplified - 'source': (opt) the URL that best represents the source of the map - 'license': (opt) the license of the map - 'nameCol': (opt) the column containing the name - 'codeCol': (opt) the column containing the id code - 'altCodeCol': (opt) alternative code columns

see 'arear::mapsources' for example

...

Named arguments passed on to standardiseMap

codeCol

the name of the column containing the id or code

nameCol

the name of the column containing the label (optional - defaults to the same as codeCol)

altCodeCol

an optional column name containing another code type

codeType

the "type" of the code - optional. defaults to NA

...

not used.

Named arguments passed on to .cached

.nocache

an option to defeat the caching which can be set globally as options("cache.disable"=TRUE)

.stale

the length of time in days to keep cached data before considering it as stale. can also be set by options("cache.stale")

Value

a standard sf map

Examples

if (interactive()) {
  map = getMap("NHSER20")
  map %>% dplyr::glimpse()
}

interpolate a variable from one set of shapes to another

Description

interpolate a variable from one set of shapes to another

Usage

interpolateByArea(
  inputDf,
  inputShape,
  by,
  interpolateVar,
  outputShape,
  inputVars = inputDf %>% dplyr::groups(),
  outputVars = outputShape %>% dplyr::groups(),
  aggregateFn = sum
)

Arguments

inputDf

- in input data frame containing the variable(s) of interest to interpolate. Stratification of the variable can be achieved by grouping

inputShape

- an input sf map,

by

- the columns to use to join the inputDf to the map provided in inputShape. This is in the format of a dplyr join specification.

interpolateVar

- the column that we want to do areal interpolation on,

outputShape

- an output map which may be grouped by the desired output,

inputVars

- a list of columns from the inputDf (as a 'dplyr::vars(...)' list) that define the stratification of inputDf and are desired in the output. Defaults to the grouping of inputDf

outputVars

- a list of columns from the outputShape (as a 'dplyr::vars(...)' list) that we want preserved in output, or defined as a grouping of outputShape

aggregateFn

- a function that will be applied to area weighted components of interpolateVar - defaults to sum

Value

a dataframe containing the grouping columns in 'inputVars' and 'outputVars', and the interpolated value of 'interpolateVar'


List the standard maps available to download

Description

List the standard maps available to download

Usage

listStandardMaps()

Value

a vector of map names

Examples

# example code
listStandardMaps()

An outline of the London NHSER region for use as a mask

Description

Data available under open government licence: http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/

Usage

londonShape

Format

A sf geometry with 1 row:

codeType

NHSER

code

E4000003 - the NHSER code for London

name

London

altCode

NA

area

the area

geometry

the outline


Locations of UK and international shapefiles relevant to COVID

Description

A list of URLs to get maps, and metadata about the maps in the shapefiles and the column labelling.

Usage

mapsources

Format

A list with:

source

the human readable location of the map

url

the web location of the downloadable map shapefile

mapName

the name of the map contained in the shapefile (which can contain multiple maps)

codeCol

the name of the shapefile column containing the code of the area

nameCol

the name of the shapefile column containing the name of the area

altCodeCol

the name of the shapefile column containing the an alternative code for the area

simplify

should the map be simplified when loaded?

license

license terms


A map theme to remove extraneous clutter

Description

A map theme to remove extraneous clutter

Usage

mapTheme()

Examples

ggplot2::ggplot(arear::testdata$gridDemand)+
  ggplot2::geom_sf(ggplot2::aes(fill=demand))+
  mapTheme()

Create a map, usually as a chloropleth, with selected areas labelled.

Description

This can be used to pick out specific highlighted regions based on a filter, label it on a map using a short code, and provide a tabular lookup of label to full name.

Usage

plotLabelledMap(
  data,
  mapping,
  ...,
  labelMapping,
  labelStyle = list(),
  labelSort = NULL,
  labels = 6,
  labelSize = 6,
  tableSize = 6,
  labelInset = c("both", "inset", "main")
)

Arguments

data

A sf object with some data in it. If using facets this should be grouped. (and if it is grouped faceting will be automatically added)

mapping

the aesthetics as would be passed to 'geom_sf'

...

additional formatting parameters as would be passed to 'geom_sf' (defaults to a thin grey line for the edge of the maps.)

labelMapping

the aesthetics of the label layer. This could include any aesthetics that apply to 'ggrepel::geom_label_repel' other than 'x','y'.. It must include a label aesthetic (which will go on the map) and a name aesthetic (which will go in the lookup table)

labelStyle

any additional formatting parameters that would be passed to 'ggrepel::geom_label_repel'. Defaults to a blue label on a light transparent background which works for dark maps. A 'list(segment.colour = "cyan", colour="cyan", fill=="#000000A0")' should give a cyan label on a dark transparent background which might work for lighter maps.

labelSort

(optional) how should we sort the labels . This defaults to the descending order of the same variable that determines the fill of the main map. This should be a simple expression that you might use for 'dplyr::arrange' and can include 'desc' for descending.

labels

how many labels do you want, per facet. The default 6 is good for a small number of facets. This will be overridden if 'labelFilter' is specified

labelSize

in points.

tableSize

the labels and the other data from all facets will be assembled into a table as a ggplot/patchwork object. This defines the font size (in points) of this table. No other config is allowed.

labelInset

if a map has an zoomed in inset as produced by 'popoutArea()', for areas which are in both the main map and the inset you may wish to label only the zoomed area in the "inset", only the unzoomed area in the "main" map or "both" (the default).

Value

a list containing 4 items. Plot and legend may be added together to form a ggplot patchwork. e.g. 'p = plotLabelledMap(...)' then 'p$plot+ggplot2::scale_fill_viridis_c()+ggplot2::facet_wrap(dplyr::vars(...))+p$legend+patchwork::plot_annotation(taglevels="A")' to actually show the map.

plot

a ggplot object showing a chloropleth (usually) which is defined by the main mapping aesthetics, with an overlaid labelling layer defined by the 'labelMapping' label aesthetic. This does not include fill or colour scales so you will probably want 'plot+ggplot2::scale_fill_viridis_c()' or something similar to define the fill

. If the input data is grouped this plot will be facetted by group.

legend

a ggplot patchwork containing the lookup table from labels to other data (as determined by the 'labelMapping' aesthetics)

labelDf

the filtered dataframe of the labels appearing in the labelling layer. The .x and .y columns are added which show where the label is placed on the main map. the .label and .name show the labels and names respectively

labeller

A function that returns a layer of the labels, formatted in same way as the main map. the labeller function takes optional xVar and yVar parameter which are columns in the sf object. These define the x and y aesthetics of the labeller and default to the same position as the main map. The labeller function can be used to add a labels layer to a different map, or to a different graph. This might be useful if you want to combine cartograms with points of interest and have them consistently labelled.

Examples

# create some test data:
tmp = dplyr::bind_rows(lapply(1:4,
  function(i) testdata$diamond11x11 %>%
    dplyr::mutate(set = sprintf("set %d",i), value = runif(x)
))) %>% dplyr::group_by(set) %>%
  dplyr::mutate(name = sprintf("%s-%s", letters[x+6], letters[y+6]))

ggplot2::ggplot(tmp)+ggplot2::geom_sf(ggplot2::aes(fill = value))+
  ggplot2::facet_wrap(~set)

p = plotLabelledMap(
  data = tmp,
  mapping = ggplot2::aes(fill = value),
  labelMapping = ggplot2::aes(label=name,percent=sprintf("%1.1f%%",value*100)),
  labels = 2
)

p$plot+p$legend

Create a magnified pop-out panel of a map

Description

Create a new map with a pop-out panel to show areas where there is a high density of people for example. Defaults work well for London on an England only map.

Usage

popoutArea(
  shape,
  popoutShape = arear::londonShape,
  popoutPosition = c("NE", "NW", "SE", "SW"),
  popoutScale = 3,
  nudgeX = 0.25,
  nudgeY = 0.25
)

Arguments

shape

The original shape

popoutShape

The mask shape. The outer boundary of this shape will be used as a mask to select the original shape

popoutPosition

Which corner to place the popout NE,NW,SE or SW

popoutScale

A factor to grow the popout area by. This is linear scale so the popout will appear the square of this factor bigger.

nudgeX

shift the popout panel by a small amount (in coordinate units)

nudgeY

shift the popout panel by a small amount (in coordinate units)

Value

A new map with the content intersecting the popout area duplicated, expanded and placed in the specified corner.

Examples

tmp = popoutArea(
  arear::testdata$diamond11x11 %>% dplyr::mutate(value = x+y),
  arear::testdata$offsetBox,
  popoutPosition = "NE",
  popoutScale = 1.25
)

ggplot2::ggplot(tmp)+
  ggplot2::geom_sf(ggplot2::aes(fill=value))+
  ggplot2::scale_fill_gradient2()+
  ggplot2::geom_sf(data = arear::testdata$offsetBox, alpha=0)

Preview a map with POI using leaflet

Description

Preview a map with POI using leaflet

Usage

preview(
  shape,
  shapeLabelGlue = "{name}",
  shapePopupGlue = "{code}",
  poi = NULL,
  poiLabelGlue = "{name}",
  poiPopupGlue = "{code}"
)

Arguments

shape

- the map

shapeLabelGlue

- a glue specification for the label for each shape

shapePopupGlue

- a glue specification for the popup for each shape

poi

- a list of points of interest as a sf object

poiLabelGlue

- a glue specification for the label for each poi

poiPopupGlue

- a glue specification for the popup for each poi

Value

htmlwidget


Save a 'sf' as a shapefile to disk

Description

Save a 'sf' as a shapefile to disk

Usage

saveShapefile(shape, mapId, dir = getwd(), overwrite = FALSE)

Arguments

shape

the sf shape

mapId

a mapId - will become the zip filename, and the filename of the zipped '.shp' file

dir

the directory (defaults to current working directory)

overwrite

the save function will not write over existing files unless this is set to true

Value

a the filename of the zipped shapefile

Examples

if (interactive()) {
  svc = "https://services1.arcgis.com/ESMARspQHYMw9BZ9/ArcGIS/rest/services"
  fs = sprintf("%s/%s",svc,"Countries_December_2024_Boundaries_UK_BUC/FeatureServer")
  layer = sprintf("%s/%s",fs,"0")
  map = downloadGeojson(layer)
  map %>% dplyr::glimpse()
  map2 = map %>% standardiseMap(codeCol = CTRY24CD, nameCol = CTRY24NM)
  map2 %>% dplyr::glimpse()
  saveShapefile(map2, "ctry24", dir = tempdir())
}

Standardise maps

Description

This function renames a 'sf' with a minimal set of attributes with consistent naming with 'code', 'name' and 'codeType' columns and an optional 'altCode' column. Renames all columns to be lower case, and makes sure the 'area' column is calculated. It also loses any 'Z' or 'M' layers.

Usage

standardiseMap(
  sf,
  codeCol = "code",
  nameCol = "name",
  altCodeCol = NULL,
  codeType = NA_character_,
  ...
)

Arguments

sf

a non standard map

codeCol

the name of the column containing the id or code

nameCol

the name of the column containing the label (optional - defaults to the same as codeCol)

altCodeCol

an optional column name containing another code type

codeType

the "type" of the code - optional. defaults to NA

...

not used.

Value

a standardised map with exactly the following columns: 'code', 'codeType', 'name', 'altCode', 'geometry' and 'area'

Examples

# example code
if (interactive()) {
  svc = "https://services1.arcgis.com/ESMARspQHYMw9BZ9/ArcGIS/rest/services"
  fs = sprintf("%s/%s",svc,"Countries_December_2024_Boundaries_UK_BUC/FeatureServer")
  layer = sprintf("%s/%s",fs,"0")
  map = downloadGeojson(layer)
  map %>% dplyr::glimpse()
  map2 = map %>% standardiseMap(codeCol = CTRY24CD, nameCol = CTRY24NM)
  map2 %>% dplyr::glimpse()
}

Hospital surge capacity in COVID

Description

Locations of UK general medical hospitals in mid march 2020 with estimates of beds available and maximal surge capacity HDU beds. This was manually assembled and curated from various sources in mid march 2020 as the NHS geared up to provide additional capacity to cope with the surge in COVID cases. It is not an up to date picture of NHS capacity. It does not include mental health or community hospitals. The surge capacity seems to have been calculated quite differently in Scotland.

Usage

surgecapacity

Format

A sf geometry with:

nation

England, Wales, etc...

hospitalId

An id for the hospital

sector

NHS or independent

hospitalName

the hospital name

pcds

the UK postcode of the hospital

trustId

the NHS trust or local health board of the hospital

trustName

the NHS trust or local health board name

tier1

indicator of the role of the hospital as an acure provider

hduBeds

the number of hdu beds the hospital could have provided at maximum surge in March 2020

acuteBeds

the number of acute beds the hospital could have provided at maximum surge in March 2020


A list of regular lattice SF polygons used for testing purposes

Description

A list of regular lattice SF polygons used for testing purposes

Usage

testdata

Format

A list with:

grid5x5

5x5 grid centred on 0,0

grid11x11

11x11 grid centred on 0,0

diamond5x5

5x5 diagonal grid centred on 0,0

diamond11x11

11x11 diagonal grid centred on 0,0

gridDemand

an 11x11 grid with a demand parameter

gridSupply

a 3 point supply

gridSupply2

another 3 point supply with only 2 ids

gridSupplyViolateConstraint

a 4 point supply with 2 points in the same grid square

gridSupplyDegenerate

a 5 point supply with 2 points in the same grid square amd a different 2 points with the same id


Mid year 2019 small area estimates for adult population of England, Wales, Scotland, and Northern Ireland

Description

Small area single digit estimates are aggregated to include only over 18s, and combining gender

Usage

uk2019adultpopulation

Format

A 41740 line data frame:

code

the ONS code for the ares

name

The name for the area

codeType

the type of area (LSOA, DZ or LGD)

population

the size of the population

Details

Data available under open government licence: http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/

Source

England and Wales

https://www.ons.gov.uk/peoplepopulationandcommunity/populationandmigration/populationestimates/datasets/lowersuperoutputareamidyearpopulationestimates

Scotland

https://www.nrscotland.gov.uk/statistics-and-data/statistics/statistics-by-theme/population/population-estimates/2011-based-special-area-population-estimates/small-area-population-estimates/time-series#2018

Northern Ireland

https://www.opendatani.gov.uk/dataset/3333626e-b96e-4b90-82fb-474c6c03b868/resource/64bd8dc4-935f-4bdd-9232-90ff33f24732/


UK small area single year of age population estimates from 2019

Description

These estimates are appropriate for the majority of the pandemic, and are the highest geographical resolution estimates by single year of age that I could find.

Usage

uk2019demographics()

Value

a dataframe with age, gender, codeType, code, name and count


Small area demographics map

Description

Shape file related to the mid year 2019 small area estimates for England, Wales, Scotland, and Northern Ireland. see [uk2019demographics()]

Usage

uk2019demographicsmap()

Details

There are 10 regions (mostly in Scotland) where the demographics estimates don't align with this map. This is a small number of people.

Data available under open government licence: http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/

Value

A 41730 line data frame:

code

the ONS code for the ares

name

The name for the area

codeType

the type of area (LSOA, DZ or LGD)

altCode

NA

Source

England and Wales

https://geoportal.statistics.gov.uk/datasets/lower-layer-super-output-areas-december-2011-boundaries-ew-bgc

Scotland

https://data.gov.uk/dataset/ab9f1f20-3b7f-4efa-9bd2-239acf63b540/data-zone-boundaries-2011

Northern Ireland

https://data.gov.uk/dataset/05f72866-b72b-476a-b6f3-57bd4a768674/osni-open-data-largescale-boundaries-local-government-districts-2012


Mid year 2019 small area estimates for adult population of England, Wales, Scotland, and Northern Ireland

Description

Small area single digit estimates are aggregated to include only over 65s, and combining gender.

Usage

uk2019retiredpopulation

Format

A 41730 line data frame:

code

the ONS code for the ares

name

The name for the area

codeType

the type of area (LSOA, DZ or LGD)

population

the size of the population

Details

Data available under open government licence: http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/

Source

England and Wales

https://www.ons.gov.uk/peoplepopulationandcommunity/populationandmigration/populationestimates/datasets/lowersuperoutputareamidyearpopulationestimates

Scotland

https://www.nrscotland.gov.uk/statistics-and-data/statistics/statistics-by-theme/population/population-estimates/2011-based-special-area-population-estimates/small-area-population-estimates/time-series#2018

Northern Ireland

https://www.opendatani.gov.uk/dataset/3333626e-b96e-4b90-82fb-474c6c03b868/resource/64bd8dc4-935f-4bdd-9232-90ff33f24732/


Locations of UK bridge or ferry route start and end points

Description

geographical location of bridges / ferries UK connections. picked from https://developers.google.com/maps/documentation/javascript/examples/event-click-latlng#maps_event_click_latlng-html

Usage

ukconnections

Format

A dataframe with:

name

the connection

start.lat

the latitude of one end

start.long

the longditude of one end

end.lat

the latitude of the other end

end.long

the longditude of the other end


COVID reporting map

Description

Shape file related to the detailed level for PHE coronavirus statistical reporting in England, Wales, Scotland, and Northern Ireland on the coronavirus.gov.uk tracker. The legacy is the level at which detailed data was reported in the first wave, prior to the API and was aggregated by https://github.com/tomwhite/covid-19-uk-data

Usage

ukcovidmap(legacy = FALSE)

Arguments

legacy

use the legacy version of the map from pre coronavirus api times.

Details

This map matches the data reported by the PHE coronavirus api when it is downloading lower tier local authority regions e.g. via https://api.coronavirus.data.gov.uk/v2/data?areaType=ltla&metric=newCasesBySpecimenDate&format=csv The API has now been discontinued.

There are 2 regions here for which no data is reported in this API - the city of London & the Isles of Scilly.

Data available under open government licence: http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/

Value

A 382 line data frame (or a 335 line data frame for legacy):

code

the ONS code for the ares

name

The name for the area

codeType

the type of area (LAD19)

altCode

NA

Source

England, Wales, Scotland & NI - LAD19

https://geoportal.statistics.gov.uk/datasets/local-authority-districts-december-2019-boundaries-uk-buc

England & Wales - LAD19

https://geoportal.statistics.gov.uk/datasets/local-authority-districts-december-2019-boundaries-uk-buc

Scotland - CA19

https://www.spatialdata.gov.scot/geonetwork/srv/eng/catalog.search#/metadata/1cd57ea6-8d6e-412b-a9dd-d1c89a80ad62

Northern Ireland -LGD12

https://data.gov.uk/dataset/05f72866-b72b-476a-b6f3-57bd4a768674/osni-open-data-largescale-boundaries-local-government-districts-2012