| 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 |
NHS trust admissions data from the legacy COVID API from 2021
apiTrustsapiTrusts
A 72928 line data frame:
the ONS code for the ares
The name for the area
the type of area (LSOA, DZ or LGD)
the NHS ODS code
hospital cases
hospital cases
the count
Get feature service information from an arcgis rest service
arcgisServiceInfo(url, ...)arcgisServiceInfo(url, ...)
url |
the base rest service url |
... |
Named arguments passed on to
|
a dataframe of available feature and map services
url = "https://services1.arcgis.com/ESMARspQHYMw9BZ9/ArcGIS/rest/services" arcgisServiceInfo(url)url = "https://services1.arcgis.com/ESMARspQHYMw9BZ9/ArcGIS/rest/services" arcgisServiceInfo(url)
Clear data from the passthrough cache for complex or long running operations
cache_clear( .cache = rappdirs::user_cache_dir(utils::packageName()), .prefix = ".*", interactive = TRUE )cache_clear( .cache = rappdirs::user_cache_dir(utils::packageName()), .prefix = ".*", interactive = TRUE )
.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) |
nothing. called for side effects
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.
catchment( supplyShape, supplyIdVar = "code", supplyVar, supplyOutputVars = supplyShape %>% dplyr::groups(), demandShape, demandIdVar = "code", demandVar, growthConstant = 1.2, bridges = arear::ukconnections, outputMap = TRUE, ... )catchment( supplyShape, supplyIdVar = "code", supplyVar, supplyOutputVars = supplyShape %>% dplyr::groups(), demandShape, demandIdVar = "code", demandVar, growthConstant = 1.2, bridges = arear::ukconnections, outputMap = TRUE, ... )
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
|
a
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.
createCatchment( supplyShape, supplyIdVar = "code", supplyVar, supplyOutputVars = supplyShape %>% dplyr::groups(), demandShape, demandIdVar = "code", demandVar, growthConstant = 1.2, bridges = arear::ukconnections, outputMap = TRUE )createCatchment( supplyShape, supplyIdVar = "code", supplyVar, supplyOutputVars = supplyShape %>% dplyr::groups(), demandShape, demandIdVar = "code", demandVar, growthConstant = 1.2, bridges = arear::ukconnections, outputMap = TRUE )
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 |
a
A network of neighbouring map regions including connections due to bridges airports or ferry links, defined in the bridges input.
createNeighbourNetwork( shape, idVar = "code", bridges = arear::ukconnections, queen = FALSE, ... )createNeighbourNetwork( shape, idVar = "code", bridges = arear::ukconnections, queen = FALSE, ... )
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
|
an edge list of ids with from and to columns
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*5edges = 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
downloadGeojson(geojsonUrl, simplify = FALSE, ...)downloadGeojson(geojsonUrl, simplify = FALSE, ...)
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
Named arguments passed on to
|
the 'sf' object for this geoJson
# 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() }# 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() }
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'.
downloadMap(zipUrl, mapName = NULL, simplify = FALSE, ...)downloadMap(zipUrl, mapName = NULL, simplify = FALSE, ...)
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
|
a 'sf' object containing the map
## Not run: downloadMap( zipUrl="https://bit.ly/3A9TnR1" ) ## End(Not run)## Not run: downloadMap( zipUrl="https://bit.ly/3A9TnR1" ) ## End(Not run)
Get layer information from a feature service
featureServerInfo(url, ...)featureServerInfo(url, ...)
url |
the feature service url |
... |
Named arguments passed on to
|
a dataframe of layers
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)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.
featureServerLayerInfo(url, ...)featureServerLayerInfo(url, ...)
url |
the feature service layer url. If no layer is specified the first one is selected. |
... |
Named arguments passed on to
|
a dataframe of field names for the selected layer
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)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)
Allow basic filtering queries only at the moment. Will cache the results and handles multipart transfers.
featureServerLayerQuery( url, where = "1 = 1", select = "*", ..., limit = NULL, crs = 4326, queryParams = list() )featureServerLayerQuery( url, where = "1 = 1", select = "*", ..., limit = NULL, crs = 4326, queryParams = list() )
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
|
limit |
maximum rows to return |
crs |
the coordinate reference system |
queryParams |
additional query parameters passed to the request to the feature server |
a 'sf' of the query result
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)) }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)) }
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
getContainedIn( inputShape, outputShape, inputVars = inputShape %>% dplyr::groups(), outputVars = outputShape %>% dplyr::groups(), suffix = c(".x", ".y") )getContainedIn( inputShape, outputShape, inputVars = inputShape %>% dplyr::groups(), outputVars = outputShape %>% dplyr::groups(), suffix = c(".x", ".y") )
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() |
- a mapping as a dataframe relating the 'inputVars' columns and 'outputVars' columns
# find the hospitals in a given area. mapping = getContainedIn( inputShape = arear::surgecapacity, outputShape = arear::ukcovidmap(), inputVars = dplyr::vars(hospitalId), outputVars = dplyr::vars(code) )# find the hospitals in a given area. mapping = getContainedIn( inputShape = arear::surgecapacity, outputShape = arear::ukcovidmap(), inputVars = dplyr::vars(hospitalId), outputVars = dplyr::vars(code) )
get the intersection between to maps with ids. Caches the result in the working directory.
getIntersection( inputShape, outputShape, suffix = c(".x", ".y"), recalcArea = TRUE, ... )getIntersection( inputShape, outputShape, suffix = c(".x", ".y"), recalcArea = TRUE, ... )
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 |
a sf object representing the intersection of the input and output shapes.
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" = "~/.)
getMap(mapId = names(sources)[1], sources = arear::mapsources, ...)getMap(mapId = names(sources)[1], sources = arear::mapsources, ...)
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
Named arguments passed on to
|
a standard sf map
if (interactive()) { map = getMap("NHSER20") map %>% dplyr::glimpse() }if (interactive()) { map = getMap("NHSER20") map %>% dplyr::glimpse() }
interpolate a variable from one set of shapes to another
interpolateByArea( inputDf, inputShape, by, interpolateVar, outputShape, inputVars = inputDf %>% dplyr::groups(), outputVars = outputShape %>% dplyr::groups(), aggregateFn = sum )interpolateByArea( inputDf, inputShape, by, interpolateVar, outputShape, inputVars = inputDf %>% dplyr::groups(), outputVars = outputShape %>% dplyr::groups(), aggregateFn = sum )
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 |
a dataframe containing the grouping columns in 'inputVars' and 'outputVars', and the interpolated value of 'interpolateVar'
List the standard maps available to download
listStandardMaps()listStandardMaps()
a vector of map names
# example code listStandardMaps()# example code listStandardMaps()
Data available under open government licence: http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/
londonShapelondonShape
A sf geometry with 1 row:
NHSER
E4000003 - the NHSER code for London
London
NA
the area
the outline
A list of URLs to get maps, and metadata about the maps in the shapefiles and the column labelling.
mapsourcesmapsources
A list with:
the human readable location of the map
the web location of the downloadable map shapefile
the name of the map contained in the shapefile (which can contain multiple maps)
the name of the shapefile column containing the code of the area
the name of the shapefile column containing the name of the area
the name of the shapefile column containing the an alternative code for the area
should the map be simplified when loaded?
license terms
A map theme to remove extraneous clutter
mapTheme()mapTheme()
ggplot2::ggplot(arear::testdata$gridDemand)+ ggplot2::geom_sf(ggplot2::aes(fill=demand))+ mapTheme()ggplot2::ggplot(arear::testdata$gridDemand)+ ggplot2::geom_sf(ggplot2::aes(fill=demand))+ mapTheme()
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.
plotLabelledMap( data, mapping, ..., labelMapping, labelStyle = list(), labelSort = NULL, labels = 6, labelSize = 6, tableSize = 6, labelInset = c("both", "inset", "main") )plotLabelledMap( data, mapping, ..., labelMapping, labelStyle = list(), labelSort = NULL, labels = 6, labelSize = 6, tableSize = 6, labelInset = c("both", "inset", "main") )
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). |
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.
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.
a ggplot patchwork containing the lookup table from labels to other data (as determined by the 'labelMapping' aesthetics)
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
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.
# 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 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 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.
popoutArea( shape, popoutShape = arear::londonShape, popoutPosition = c("NE", "NW", "SE", "SW"), popoutScale = 3, nudgeX = 0.25, nudgeY = 0.25 )popoutArea( shape, popoutShape = arear::londonShape, popoutPosition = c("NE", "NW", "SE", "SW"), popoutScale = 3, nudgeX = 0.25, nudgeY = 0.25 )
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) |
A new map with the content intersecting the popout area duplicated, expanded and placed in the specified corner.
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)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
preview( shape, shapeLabelGlue = "{name}", shapePopupGlue = "{code}", poi = NULL, poiLabelGlue = "{name}", poiPopupGlue = "{code}" )preview( shape, shapeLabelGlue = "{name}", shapePopupGlue = "{code}", poi = NULL, poiLabelGlue = "{name}", poiPopupGlue = "{code}" )
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 |
htmlwidget
Save a 'sf' as a shapefile to disk
saveShapefile(shape, mapId, dir = getwd(), overwrite = FALSE)saveShapefile(shape, mapId, dir = getwd(), overwrite = FALSE)
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 |
a the filename of the zipped shapefile
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()) }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()) }
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.
standardiseMap( sf, codeCol = "code", nameCol = "name", altCodeCol = NULL, codeType = NA_character_, ... )standardiseMap( sf, codeCol = "code", nameCol = "name", altCodeCol = NULL, codeType = NA_character_, ... )
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. |
a standardised map with exactly the following columns: 'code', 'codeType', 'name', 'altCode', 'geometry' and 'area'
# 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() }# 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() }
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.
surgecapacitysurgecapacity
A sf geometry with:
England, Wales, etc...
An id for the hospital
NHS or independent
the hospital name
the UK postcode of the hospital
the NHS trust or local health board of the hospital
the NHS trust or local health board name
indicator of the role of the hospital as an acure provider
the number of hdu beds the hospital could have provided at maximum surge in March 2020
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
testdatatestdata
A list with:
5x5 grid centred on 0,0
11x11 grid centred on 0,0
5x5 diagonal grid centred on 0,0
11x11 diagonal grid centred on 0,0
an 11x11 grid with a demand parameter
a 3 point supply
another 3 point supply with only 2 ids
a 4 point supply with 2 points in the same grid square
a 5 point supply with 2 points in the same grid square amd a different 2 points with the same id
Small area single digit estimates are aggregated to include only over 18s, and combining gender
uk2019adultpopulationuk2019adultpopulation
A 41740 line data frame:
the ONS code for the ares
The name for the area
the type of area (LSOA, DZ or LGD)
the size of the population
Data available under open government licence: http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/
https://www.ons.gov.uk/peoplepopulationandcommunity/populationandmigration/populationestimates/datasets/lowersuperoutputareamidyearpopulationestimates
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
https://www.opendatani.gov.uk/dataset/3333626e-b96e-4b90-82fb-474c6c03b868/resource/64bd8dc4-935f-4bdd-9232-90ff33f24732/
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.
uk2019demographics()uk2019demographics()
a dataframe with age, gender, codeType, code, name and count
Shape file related to the mid year 2019 small area estimates for England, Wales, Scotland, and Northern Ireland. see [uk2019demographics()]
uk2019demographicsmap()uk2019demographicsmap()
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/
A 41730 line data frame:
the ONS code for the ares
The name for the area
the type of area (LSOA, DZ or LGD)
NA
https://geoportal.statistics.gov.uk/datasets/lower-layer-super-output-areas-december-2011-boundaries-ew-bgc
https://data.gov.uk/dataset/ab9f1f20-3b7f-4efa-9bd2-239acf63b540/data-zone-boundaries-2011
https://data.gov.uk/dataset/05f72866-b72b-476a-b6f3-57bd4a768674/osni-open-data-largescale-boundaries-local-government-districts-2012
Small area single digit estimates are aggregated to include only over 65s, and combining gender.
uk2019retiredpopulationuk2019retiredpopulation
A 41730 line data frame:
the ONS code for the ares
The name for the area
the type of area (LSOA, DZ or LGD)
the size of the population
Data available under open government licence: http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/
https://www.ons.gov.uk/peoplepopulationandcommunity/populationandmigration/populationestimates/datasets/lowersuperoutputareamidyearpopulationestimates
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
https://www.opendatani.gov.uk/dataset/3333626e-b96e-4b90-82fb-474c6c03b868/resource/64bd8dc4-935f-4bdd-9232-90ff33f24732/
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
ukconnectionsukconnections
A dataframe with:
the connection
the latitude of one end
the longditude of one end
the latitude of the other end
the longditude of the other end
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
ukcovidmap(legacy = FALSE)ukcovidmap(legacy = FALSE)
legacy |
use the legacy version of the map from pre coronavirus api times. |
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/
A 382 line data frame (or a 335 line data frame for legacy):
the ONS code for the ares
The name for the area
the type of area (LAD19)
NA
https://geoportal.statistics.gov.uk/datasets/local-authority-districts-december-2019-boundaries-uk-buc
https://geoportal.statistics.gov.uk/datasets/local-authority-districts-december-2019-boundaries-uk-buc
https://www.spatialdata.gov.scot/geonetwork/srv/eng/catalog.search#/metadata/1cd57ea6-8d6e-412b-a9dd-d1c89a80ad62
https://data.gov.uk/dataset/05f72866-b72b-476a-b6f3-57bd4a768674/osni-open-data-largescale-boundaries-local-government-districts-2012