| Type: | Package |
| Title: | Access, Retrieve, and Work with Canadian Census Data and Geography |
| Version: | 0.6.3 |
| Description: | Integrated, convenient, and uniform access to Canadian Census data and geography retrieved using the 'CensusMapper' API. This package produces analysis-ready tidy data frames and spatial data in multiple formats, as well as convenience functions for working with Census variables, variable hierarchies, and region selection. API keys are freely available with free registration at https://censusmapper.ca/api. Census data and boundary geometries are reproduced and distributed on an "as is" basis with the permission of Statistics Canada (Statistics Canada 1996; 2001; 2006; 2011; 2016; 2021; 2026). |
| License: | MIT + file LICENSE |
| Encoding: | UTF-8 |
| LazyData: | yes |
| ByteCompile: | yes |
| NeedsCompilation: | no |
| Imports: | digest (≥ 0.1), dplyr (≥ 1.0), httr (≥ 1.0.0), jsonlite (≥ 1.0), sf, geojsonsf, rlang (≥ 1.0.0), readr (≥ 2.0.0) |
| Suggests: | DBI, duckdb (≥ 1.5.6), knitr, ggplot2, grid, leaflet, mapdeck, RColorBrewer, rmarkdown, safeconduct (≥ 0.1.0), scales, sp, transport, tricolore, viridisLite, systemfonts, tidyr, lwgeom, xml2, testthat (≥ 3.0.0), microbenchmark |
| VignetteBuilder: | knitr |
| URL: | https://github.com/mountainMath/cancensus, https://mountainmath.github.io/cancensus/, https://censusmapper.ca/api |
| BugReports: | https://github.com/mountainMath/cancensus/issues |
| Depends: | R (≥ 4.1) |
| Config/roxygen2/version: | 8.1.0 |
| Packaged: | 2026-11-25 03:40:58 UTC; jens |
| Author: | Jens von Bergmann [aut] (API creator and maintainer), Dmitry Shkolnik [aut, cre] (Package maintainer, responsible for correspondence), Aaron Jacobs [aut] |
| Maintainer: | Dmitry Shkolnik <shkolnikd@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-25 10:00:02 UTC |
A dataset with code table summaries for census data
Description
The census division and census subdivision types (the municipal_status
of regions) of the 1981 to 2026 censuses, with the most recent description
of each code.
Author(s)
derived from StatCan definitions
References
https://www12.statcan.gc.ca/census-recensement/2026/geo/ref/domain-domaine/index2026-eng.cfm?lang=e&id=CSDTYPE, https://www12.statcan.gc.ca/census-recensement/2026/geo/ref/domain-domaine/index2026-eng.cfm?lang=e&id=CDTYPE, https://www12.statcan.gc.ca/census-recensement/2021/geo/ref/domain-domaine/index2021-eng.cfm?lang=e&id=CSDTYPE, https://www150.statcan.gc.ca/n1/pub/92-151-g/2011001/tech-eng.htm, https://www12.statcan.gc.ca/census-recensement/2006/ref/dict/tables-tableaux-eng.cfm, https://www12.statcan.gc.ca/english/census01/Products/Reference/dict/geo012.htm, https://www.statcan.gc.ca/en/subjects/standard/sgc/1996/1996-info-rens, https://www12.statcan.gc.ca/access_acces/push_pdf.cfm?FILE_REQUESTED=%5CEnglish%5Ccensus86%5Creference&File_Name=CS99-101-1987-eng.pdf
A dataset City of Vancouver skytrain station locations
Description
A dataset City of Vancouver skytrain station locations
Author(s)
City of Vancouver Open Data
References
https://opendata.vancouver.ca/explore/dataset/rapid-transit-stations/information/
Convenience function for creating unique names from region list
Description
Names of municipalities are not always unique, especially at the CSD level. This function takes as input a subset of a regions list as generated from 'list_census_regions()' and de-duplicates names as needed by adding the municipal status in parenthesis. If this does not de-duplicate the name then the geographic identifier will be further added in parenthesis behind that.
Usage
add_unique_names_to_region_list(region_list)
Arguments
region_list |
a subset of a regions list as gotten from 'list_census_regions()' |
Value
The same list of regions with an extra column 'Name' with de-duplicated names.
Examples
## Not run:
# This will return a warning that no match was found, but will suggest similar named regions.
library(dplyr)
list_census_regions("CA21") %>%
filter(level=="CSD", CMA_UID=="59933") %>%
add_unique_names_to_region_list()
## End(Not run)
Convert a (suitably filtered) data frame from
list_census_regions to a list suitable for passing to
get_census.
Description
Convert a (suitably filtered) data frame from
list_census_regions to a list suitable for passing to
get_census.
Usage
as_census_region_list(tbl)
Arguments
tbl |
A data frame, suitably filtered, as returned by
|
Examples
## Not run:
library(dplyr, warn.conflicts = FALSE)
# Query the CensusMapper API for the total occupied dwellings
# of 20 random Census Subdivisions, in Census 2016.
regions <- list_census_regions("CA16") %>%
filter(level == "CSD") %>%
sample_n(20) %>%
as_census_region_list()
occupied <- get_census("CA16", regions = regions,
vectors = c("v_CA16_408"),
level = "Regions")
## End(Not run)
User agent sent with CensusMapper API requests
Description
Identifies the package and its version to the CensusMapper API, in the form 'cancensus/<version> httr/<version> R/<version>'. Packages or tools building on **cancensus** can identify themselves by setting the 'cancensus.user_agent_prefix' option, e.g. 'options(cancensus.user_agent_prefix = "mypackage/1.2.3")', which gets prepended to the user agent string.
Usage
cancensus_user_agent()
Value
A character string
Return Census variable names and labels as a tidy data frame (Deprecated)
Description
Return Census variable names and labels as a tidy data frame (Deprecated)
Usage
census_vectors(x)
Arguments
x |
A data frame, |
Value
A data frame with a column variable containing the truncated
variable name, and a column label describing it.
Examples
## Not run:
# Query census data with truncated labels:
census_data <- get_census(dataset='CA16', regions=list(CMA="59933"),
vectors=c("v_CA16_408","v_CA16_409","v_CA16_410"),
level='CSD', geo_format = "sf", labels="short")
# Get details for truncated vectors:
census_vectors(census_data)
## End(Not run)
List all child variables from vector hierarchies given either a list of Census
variables returned by
list_census_vectors, search_census_vectors, find_census_vectors, or a direct string reference to the vector code.
Description
List all child variables from vector hierarchies given either a list of Census
variables returned by
list_census_vectors, search_census_vectors, find_census_vectors, or a direct string reference to the vector code.
Usage
child_census_vectors(
vector_list,
leaves_only = FALSE,
max_level = NA,
keep_parent = FALSE,
language = NULL
)
Arguments
vector_list |
the list of vectors to be used, either a character vector or a filtered tibble
as returned from |
leaves_only |
boolean flag to indicate if only final leaf vectors should be returned, i.e. terminal vectors that themselves do not have children. |
max_level |
optional, maximum depth to look for child vectors. Default is |
keep_parent |
optional, also return parent vector in list of results. Default is set to |
language |
Language of the labels, one of |
Examples
# Query parent vectors directly using vector identifier
child_census_vectors("v_CA16_2510")
## Not run:
# Example using multiple vectors coerced into a list
child_census_vectors(c("v_CA16_2510","v_CA16_2511","v_CA16_2512"))
# or, equivalently
selected_vectors <- c("v_CA16_2510","v_CA16_2511","v_CA16_2512")
child_census_vectors(selected_vectors)
# Example using dplyr and piped arguments
library(dplyr, warn.conflicts = FALSE)
list_census_vectors("CA16") %>%
filter(vector == "v_CA16_2510") %>%
child_census_vectors(TRUE)
# this will return the equivalent of c("v_CA16_2510", child_census_vectors("v_CA16_2510"))
list_census_vectors("CA16") %>%
filter(vector == "v_CA16_2510") %>%
child_census_vectors(TRUE, keep_parent = TRUE)
## End(Not run)
Quantile from brackets, as on CensusMapper
Description
CensusMapper's binned_quantile() (and quantile()): the
p-quantile, e.g. the median income, from counts per bracket and the brackets'
lower cutoffs, interpolating linearly within the bracket. The lowest bracket
starts at 0 and the top bracket ends at twice its lower cutoff.
Usage
cm_binned_quantile(counts, lower_cutoffs, p)
Arguments
counts |
Counts per bracket: a matrix with one row per region and one
column per bracket, e.g. |
lower_cutoffs |
The brackets' lower cutoffs, a vector that is the same
for every region, or a matrix like |
p |
The quantile, between 0 and 1, the same for every region or one per region. |
Value
A numeric vector with one value per region, NA where any input is missing and NaN where there are no counts.
Examples
cm_binned_quantile(cbind(c(10, 5), c(20, 10), c(5, 20)), c(0, 20000, 50000), 0.5)
The features of CensusMapper's base map as sf data
Description
Gets the features of CensusMapper's base map for the extent of some sf data
or a bounding box from CensusMapper's vector tiles: water, landcover,
landuse, airports, buildings, roads, and places and road labels. These are
the features geom_cm_context() draws, unstyled, for drawing
them in other ways or with other mapping packages.
Usage
cm_context(
data,
layers = c("water", "landcover", "landuse", "aeroway", "buildings", "roads", "places",
"road_labels"),
zoom = NULL,
pixels = 800,
language = getOption("cancensus.language", "en"),
tile_server = "https://censusmapper.ca",
api_key = Sys.getenv("CM_API_KEY")
)
Arguments
data |
sf data, an sfc or a bounding box whose extent to get the base map for. |
layers |
Which layers to get, any of |
zoom |
Zoom level (as on CensusMapper) whose tiles to use. By default
the zoom level at which the data spans |
pixels |
The width, in pixels, of the CensusMapper map whose zoom level to use. |
language |
Language of the names, |
tile_server |
Where to get the tiles from. |
api_key |
An API key for the CensusMapper API. Defaults to the
|
Details
The tiles, and with them the detail of the features, are those CensusMapper
uses at the zoom level at which the data spans pixels pixels, or at
zoom. Which classes of features exist at a zoom level is decided by
the tiles; geom_cm_context() additionally shows some classes
(minor roads, buildings, road labels) only at higher zoom levels.
Tiles are downloaded from the tile server and cached for the session. They need a CensusMapper API key, the same as for the census data, though tiles count against a separate tile quota. Needs GDAL with its MVT driver for sf to read the tiles.
Value
A named list with an sf data frame for each layer, in the CRS of
data and cropped to its bounding box. A layer without features is an
sf data frame without rows. Features have their class, and places and
road labels their name in the language language (or the local
name). Road labels are points along named roads, with the angle (in
degrees) to turn labels by and the length of the road (in metres). The
other columns come from the tiles and may change. The zoom level is in the
"zoom" attribute.
See Also
geom_cm_context() to add the base map to a ggplot map.
Examples
## Not run:
library(ggplot2)
census_data <- get_census("CA21", regions = list(CSD = "5915022"),
vectors = c(population = "v_CA21_1"),
level = "DA", geo_format = "sf")
context <- cm_context(census_data, layers = c("water", "roads", "places"))
major <- context$roads[context$roads$class %in% c("motorway", "trunk", "primary"), ]
ggplot(census_data) +
geom_sf(aes(fill = population / `Shape Area`), colour = NA) +
geom_sf(data = context$water, fill = "lightblue", colour = NA) +
geom_sf(data = major, colour = "grey30") +
geom_sf_text(data = context$places[context$places$class == "suburb", ],
aes(label = name), size = 3) +
coord_sf(datum = NA)
## End(Not run)
Gini coefficient from income brackets, as on CensusMapper
Description
CensusMapper's gini(): the Gini coefficient from counts per income
bracket and the brackets' lower cutoffs, one value per region. Incomes are
taken at the bracket midpoints. The top bracket's income is twice its lower
cutoff less the previous cutoff, or is estimated from the total income when
that is given.
Usage
cm_gini(counts, lower_cutoffs, total = 0)
Arguments
counts |
Counts per bracket: a matrix with one row per region and one
column per bracket, e.g. |
lower_cutoffs |
The brackets' lower cutoffs, a vector that is the same
for every region, or a matrix like |
total |
Total income per region, or 0 (the default) for none. |
Value
A numeric vector with one value per region, NA where any input is missing.
Examples
cm_gini(cbind(c(10, 5), c(20, 10), c(5, 20)), c(0, 20000, 50000))
Gini coefficient from income brackets, CensusMapper's gini2()
Description
Like cm_gini, but the top bracket's income total is the larger
of its estimate from the bracket width and what the total income leaves
after the other brackets.
Usage
cm_gini2(counts, lower_cutoffs, total = 0)
Arguments
counts |
Counts per bracket: a matrix with one row per region and one
column per bracket, e.g. |
lower_cutoffs |
The brackets' lower cutoffs, a vector that is the same
for every region, or a matrix like |
total |
Total income per region, or 0 (the default) for none. |
Value
A numeric vector with one value per region, NA where any input is missing.
Examples
cm_gini2(cbind(c(10, 5), c(20, 10), c(5, 20)), c(0, 20000, 50000), c(1e6, 2e6))
Colours for three-part compositions, as on CensusMapper
Description
Colours for compositions of three parts, e.g. the shares of children,
working age population and seniors, with the balance scheme of the
tricolore package, as used by CensusMapper's ternary ("rgb") maps. The
colours are the same as tricolore::Tricolore()'s, with the
parameters in CensusMapper's units, the same as in a CensusMapper map's
tricolore_options.
Usage
cm_tricolore(
p1,
p2,
p3,
center = rep(1/3, 3),
breaks = 3,
hue = 60,
chroma = 200,
lightness = 80,
contrast = 0.4,
spread = 1
)
Arguments
p1, p2, p3 |
The three parts, as counts or shares; they are divided by
their total. Compositions with missing or negative parts, or a total of
zero, get |
center |
The composition that gets the neutral (grey) colour, e.g. the composition of the whole region. By default the centre of the triangle. |
breaks |
The number of breaks along each side of the triangle for
discrete colours, |
hue |
The hue of the first part, in degrees (0 to 360); the other parts are 120 and 240 degrees further. |
chroma |
The maximum chroma (CIE-LUV, 0 to 200). Above about 75 some colours are outside the sRGB gamut and are clipped. |
lightness |
The lightness (0 to 100). |
contrast |
How much less light and chroma compositions near the centre get (0 to 1). |
spread |
How spread out the colours are around the centre (> 0). |
Details
With discrete colours (finite breaks) the triangle of compositions is
split into breaks^2 triangles, and each composition gets the colour
of the centroid of its triangle. The center changes the colours of
these triangles, but not their shape.
Value
A character vector of colours ("#RRGGBB"), one for each
composition.
References
Schöley, J. (2021). The centered ternary balance scheme: A technique to visualize surfaces of unbalanced three-part compositions. Demographic Research, 44(19), 443–458. doi:10.4054/DemRes.2021.44.19
See Also
geom_cm_tricolore() for a ggplot map with these
colours and a colour key.
Examples
cm_tricolore(c(0.2, 0.5, 1), c(0.6, 0.3, 1), c(0.2, 0.2, 1))
Wasserstein distance per region, as on CensusMapper
Description
CensusMapper's wasserstein(): the p-Wasserstein distance between two
samples of the same size for each region, using
transport::wasserstein1d(). Needs the transport package.
Usage
cm_wasserstein(a, b, p = 1)
Arguments
a, b |
The samples: matrices with one row per region, e.g.
|
p |
The order of the distance, the same for every region or one per region. |
Value
A numeric vector with one value per region, NA where any input is missing.
Examples
if (requireNamespace("transport", quietly = TRUE)) {
cm_wasserstein(cbind(c(1, 2), c(3, 4)), c(2, 2))
}
Show the area of a bounding box on a ggplot map
Description
A ggplot2::coord_sf() that limits a map to a bounding box, e.g. the
area of a CensusMapper map's view, while the data can extend beyond it. The
box can be in any CRS: it is turned into the map's CRS. With
bbox = NULL the map shows all its data, as with coord_sf(),
so that cropping is switched off by setting the box to NULL.
geom_cm_context() covers the area shown.
Usage
coord_cm_bbox(bbox = NULL, crs = NULL, datum = NA, ...)
Arguments
bbox |
The area to show: a bounding box ( |
crs |
The CRS of the map. By default that of the map's data. |
datum |
The CRS of the graticule; by default none. |
... |
Other arguments passed on to |
Value
An object to add to a ggplot with +.
Examples
## Not run:
library(ggplot2)
census_data <- get_census("CA21", regions = list(CMA = "59933"),
vectors = c(population = "v_CA21_1"),
level = "CT", geo_format = "sf")
view_bbox <- sf::st_bbox(c(xmin = -123.19, ymin = 49.24, xmax = -123.05, ymax = 49.30),
crs = 4326)
ggplot(census_data) +
geom_sf(aes(fill = population / `Shape Area`), colour = NA) +
geom_cm_context() +
coord_cm_bbox(view_bbox)
## End(Not run)
Get attribution for datasets
Description
Get attribution for datasets
Usage
dataset_attribution(datasets, language = getOption("cancensus.language", "en"))
Arguments
datasets |
Vector of dataset identifiers |
language |
Language of the attribution, one of |
Value
Returns a string to be used as attribution for the given datasets.
Examples
## Not run:
# Attribution string for the 2006 and 2016 census datasets
dataset_attribution(c('CA06','CA16'))
## End(Not run)
Interactively browse Census variables and regions on Censusmapper.ca in a new browser window
Description
Finding the right Census variables or regions can be complicated.
explore_census_vectors(dataset) and explore_census_regions(dataset) will open a
new browser page or tab to an interactive Census variable and region exploration and selection
tool on the Censusmapper.ca website. Interactive
tools available for the CA16, CA11, CA06, and CA01 Census datasets and geographies.
Usage
explore_census_regions(dataset = "CA16")
Arguments
dataset |
The dataset to query for available vectors, e.g. |
Examples
## Not run:
explore_census_vectors(dataset = "CA16")
explore_census_regions(dataset = "CA21")
## End(Not run)
Interactively browse Census variables and regions on Censusmapper.ca in a new browser window
Description
Finding the right Census variables or regions can be complicated.
explore_census_vectors(dataset) and explore_census_regions(dataset) will open a
new browser page or tab to an interactive Census variable and region exploration and selection
tool on the Censusmapper.ca website. Interactive
tools available for the CA16, CA11, CA06, and CA01 Census datasets and geographies.
Usage
explore_census_vectors(dataset = "CA21")
Arguments
dataset |
The dataset to query for available vectors, e.g. |
Examples
## Not run:
explore_census_vectors(dataset = "CA16")
explore_census_regions(dataset = "CA21")
## End(Not run)
Query the CensusMapper API for vectors using exact, semantic, or keyword search
Description
Query the available list of Census vectors based on their label and return
details including vector code. Default search behaviour expects an exact match, but
keyword or semantic searches can be used instead by setting query_type='keyword' or
query_type = 'semantic' instead. Keyword search is useful when looking to explore
Census vectors based on broad themes like "income" or "language". Keyword search separates
the query into unigrams and returns Census vectors with matching words, ranked by incidence
of matches. Semantic search is designed for more precise searches while allowing room for error
for spelling or phrasing, as well as for finding closely related vector matches. Semantic search
separates the query into n-grams and relies on string distance measurement using a generalized
Levenshtein distance approach.
Some census vectors return population counts segmented by Female and Male populations, in
addition to a total aggregate. By default, query matches will return matches for the Total
aggregation, but can optionally return only the Female or Male aggregations by adding
type = 'female' or type = 'male' as a parameter.
Usage
find_census_vectors(
query,
dataset,
type = "all",
query_type = "exact",
...,
language = getOption("cancensus.language", "en")
)
Arguments
query |
The term or phrase to search for e.g. |
dataset |
The dataset to query for available vectors, e.g. |
type |
One of |
query_type |
One of |
... |
Other arguments passed to internal functions. |
language |
Language to search in and return labels in, one of |
Examples
## Not run:
find_census_vectors('Oji-cree', dataset = 'CA16', type = 'total', query_type = 'exact')
find_census_vectors('commuting duration', dataset = 'CA11', type = 'female', query_type = 'keyword')
find_census_vectors('after tax income', dataset = 'CA16', type = 'total', query_type = 'semantic')
# This incorrect spelling will return a warning that no match was found,
# but will suggest trying semantic or keyword search.
find_census_vectors('Ojibwey', dataset = 'CA16', type = 'total')
# This will find near matches as well
find_census_vectors('Ojibwey', dataset = 'CA16', type = 'total', query_type = "semantic")
find_census_vectors('commute duration', dataset = 'CA16', type = 'female', query_type = 'keyword')
find_census_vectors('commute duration', dataset = 'CA11', type = 'all', query_type = 'keyword')
find_census_vectors('ukrainian origin', dataset = 'CA16', type = 'total', query_type = 'keyword')
find_census_vectors('revenu total', dataset = 'CA16', type = 'total',
query_type = 'keyword', language = 'fr')
## End(Not run)
Format bytes to human-readable size
Description
Format bytes to human-readable size
Usage
format_bytes(bytes, language = NULL)
Arguments
bytes |
Number of bytes |
language |
Language for units and decimal mark, see |
CensusMapper's base map for a ggplot map
Description
Adds CensusMapper's base map on top of a map of census data: landuse
(semi-transparent, so the data shows through), water, buildings (at high
zoom only), roads and place and road labels, drawn from CensusMapper's vector
tiles and styled like the maps on censusmapper.ca. As on CensusMapper, add it
after the geom_sf() with the census data, which it draws over.
Usage
geom_cm_context(
layers = c("landuse", "water", "buildings", "roads", "labels"),
zoom = NULL,
pixels = 800,
scale = 1,
language = getOption("cancensus.language", "en"),
family = NULL,
tile_server = "https://censusmapper.ca"
)
Arguments
layers |
Which parts of the base map to draw, any of |
zoom |
Zoom level (as on CensusMapper) to draw the base map at. By
default the zoom level at which the area shown spans |
pixels |
The width, in pixels, of the CensusMapper map the plot mimics. Larger values show more detail, with relatively smaller lines and labels. |
scale |
Factor to make lines and labels larger or smaller. |
language |
Language of the labels, |
family |
Font family of the labels. By default "Noto Sans", as on CensusMapper, if the systemfonts package finds it, otherwise "sans". |
tile_server |
Where to get the tiles from. |
Details
The map looks like CensusMapper showing the data in a window pixels
wide (or at zoom), scaled to the size of the plot's panel when it is
drawn: that zoom level decides which features, roads and labels are shown,
and lines and labels keep their size relative to the map whatever size the
plot is drawn at. Labels are thinned out so that they don't overlap.
The base map covers the area the plot shows: by default all its sf data, or
the limits set with coord_cm_bbox() or
ggplot2::coord_sf(). It is drawn in the plot's CRS, whatever CRS the
data are in.
The tiles are downloaded when the plot is drawn and cached for the session.
They need a CensusMapper API key, the same as for the census data, though
tiles count against a separate tile quota. The key is taken from the
CM_API_KEY environment variable, set with
set_cancensus_api_key().
Without an API key the plot is drawn without the base map, with a warning.
Needs the ggplot2 package, and GDAL with its MVT driver for sf to read the
tiles. To style the base map differently, or to use it with other mapping
packages, get its features with cm_context().
Value
An object to add to a ggplot with +.
See Also
cm_context() for the features of the base map as sf data.
Examples
## Not run:
library(ggplot2)
census_data <- get_census("CA21", regions = list(CSD = "5915022"),
vectors = c(population = "v_CA21_1"),
level = "DA", geo_format = "sf")
ggplot(census_data) +
geom_sf(aes(fill = population / `Shape Area`), colour = NA) +
scale_fill_viridis_c(trans = "log") +
geom_cm_context() +
coord_sf(datum = NA)
## End(Not run)
A ggplot map of three-part compositions, as on CensusMapper
Description
Maps compositions of three parts, e.g. the shares of children, working age
population and seniors, in the colours of CensusMapper's ternary ("rgb")
maps (see cm_tricolore()), with a triangular colour key: a
ggplot2::geom_sf() layer with the colours as fill, and the key as a
legend. The key shows the colours of compositions, the first part at the
top, the second bottom left and the third bottom right, and the regions as
dots.
Usage
geom_cm_tricolore(
mapping = NULL,
data = NULL,
...,
labels = NULL,
name = NULL,
center = rep(1/3, 3),
breaks = 3,
hue = 60,
chroma = 200,
lightness = 80,
contrast = 0.4,
spread = 1,
na.value = "grey60",
show_data = TRUE,
key_size = 3,
show.legend = TRUE
)
Arguments
mapping |
Aesthetics made with |
data |
The data for the layer, sf data; by default the plot's data. |
... |
Other arguments passed on to |
labels |
Labels for the three parts on the key. By default the
expressions for |
name |
The title of the key, by default none. |
center |
The composition that gets the neutral (grey) colour, e.g. the composition of the whole region. By default the centre of the triangle. |
breaks |
The number of breaks along each side of the triangle for
discrete colours, |
hue |
The hue of the first part, in degrees (0 to 360); the other parts are 120 and 240 degrees further. |
chroma |
The maximum chroma (CIE-LUV, 0 to 200). Above about 75 some colours are outside the sRGB gamut and are clipped. |
lightness |
The lightness (0 to 100). |
contrast |
How much less light and chroma compositions near the centre get (0 to 1). |
spread |
How spread out the colours are around the centre (> 0). |
na.value |
The colour for regions without a composition. |
show_data |
Whether to show the regions as dots on the key. |
key_size |
The width of the key, in cm. |
show.legend |
Whether to show the key. |
Details
The fill colours are set directly, not through a fill scale, so the plot
can still have a fill scale for other layers. Regions without a composition
(missing or negative parts, or a total of zero) are na.value. The
compositions are computed from the layer's data, or the plot's data if the
layer has none, when the layer is added to the plot.
Value
An object to add to a ggplot with +.
See Also
cm_tricolore() for just the colours.
Examples
## Not run:
library(ggplot2)
census_data <- get_census("CA21", regions = list(CMA = "59933"),
vectors = c(children = "v_CA21_11",
working_age = "v_CA21_68",
seniors = "v_CA21_251"),
level = "CT", geo_format = "sf")
ggplot(census_data) +
geom_cm_tricolore(aes(p1 = children, p2 = working_age, p3 = seniors),
labels = c("0 to 14", "15 to 64", "65 and over"),
colour = NA) +
geom_cm_context() +
coord_sf(datum = NA)
## End(Not run)
Access to Canadian census data through the CensusMapper API
Description
This function allows convenient access to Canadian census data and boundary files through the CensusMapper API. An API key is required to retrieve data.
Usage
get_census(
dataset,
regions,
level = NA,
vectors = c(),
geo_format = NA,
resolution = "simplified",
labels = getOption("cancensus.labels", "detailed"),
use_cache = TRUE,
quiet = FALSE,
api_key = Sys.getenv("CM_API_KEY"),
retry = 0,
language = getOption("cancensus.language", "en")
)
Arguments
dataset |
A CensusMapper dataset identifier. |
regions |
A named list of census regions to retrieve. Names must be valid census aggregation levels. |
level |
The census aggregation level to retrieve, defaults to |
vectors |
An R vector containing the CensusMapper variable names of the census variables to download. If no vectors are specified only geographic data will get downloaded. Naming the elements of the vector sets the names of the columns, e.g. |
geo_format |
By default is set to |
resolution |
Resolution of the geographic data. By default simplified geometries will be download. For lower level geometries like DB or DA this will be very close to the high resolution data.
Simplification generally increases as the geographic aggregation level increases.
If high resolution geometries are required
then this option can be set to 'high'. By default this setting is set to |
labels |
Defaults to the |
use_cache |
If set to TRUE (the default) data will be read from the local cache if available. |
quiet |
When TRUE, suppress messages and warnings. |
api_key |
An API key for the CensusMapper API. Defaults to |
retry |
Integer If greater than zero, automatically retry API requests that fail with a network error or a transient server error (HTTP 408, 502 or 504) with exponential backoff for specified maximum number of times. Defaults to 0. Requests are always retried at least twice when the server is busy (HTTP 503 or 429), waiting as long as the server asks. |
language |
Language of the Census variable labels, one of |
Details
For help selecting regions and vectors, see list_census_regions
and list_census_vectors, or check out the interactive selection
tool at https://censusmapper.ca/api by calling explore_census_vectors()
Each region is identified by its GeoUID, and also by its Statistics Canada Dissemination Geography
Unique Identifier in the DGUID column, right after GeoUID. DGUIDs are character strings like
"2021S051259150004" for a dissemination area, and NA for regions that don't have one, like those of
the CA1116 dataset. Enumeration areas (CA1991 and CA1996) get CensusMapper codes of the same form with type
X. Data downloaded before the CensusMapper API added DGUIDs doesn't have this column, use
use_cache = FALSE to download it again.
Source
Census data and boundary geographies are reproduced and distributed on an "as is" basis with the permission of Statistics Canada (Statistics Canada 1996; 2001; 2006; 2011; 2016).
Examples
# Query the API for data on dwellings in Vancouver, at the census subdivision
# level:
## Not run:
census_data <- get_census(dataset='CA16', regions=list(CMA="59933"),
vectors=c("v_CA16_408","v_CA16_409","v_CA16_410"),
level='CSD')
# Query the API for data on dwellings in Vancouver, at the census subdivision
# level, and return the associated geography files in \code{sf} format:
census_data <- get_census(dataset='CA16', regions=list(CMA="59933"),
vectors=c("v_CA16_408","v_CA16_409","v_CA16_410"),
level='CSD', geo_format = "sf")
# Make the same query, but this time drop descriptive vector names:
census_data <- get_census(dataset='CA16', regions=list(CMA="59933"),
vectors=c("v_CA16_408","v_CA16_409","v_CA16_410"),
level='CSD', geo_format = "sf", labels="short")
# Get details for truncated vectors:
label_vectors(census_data)
# Name columns by vector, with the labels in the "label" attribute of the columns:
census_data <- get_census(dataset='CA16', regions=list(CMA="59933"),
vectors=c("v_CA16_408","v_CA16_409","v_CA16_410"),
level='CSD', labels="labelled")
attr(census_data$v_CA16_408, "label")
# Get the labels in French:
census_data <- get_census(dataset='CA16', regions=list(CMA="59933"),
vectors=c("v_CA16_408","v_CA16_409","v_CA16_410"),
level='CSD', language="fr")
## End(Not run)
Deprecated, use 'get_census' instead
Description
This function will be removed in future versions.
Usage
get_census_geometry(dataset, regions, level = NA, geo_format = "sf", ...)
Arguments
dataset |
A CensusMapper dataset identifier. |
regions |
A named list of census regions to retrieve. Names must be valid census aggregation levels. |
level |
The census aggregation level to retrieve, defaults to |
geo_format |
By default is set to |
... |
Further arguments passed to |
Source
Census data and boundary geographies are reproduced and distributed on an "as is" basis with the permission of Statistics Canada (Statistics Canada 2006; 2011; 2016).
Examples
# Query the API for data geographies in Vancouver, at the census subdivision
# level:
## Not run:
# Query the API for geographies in Vancouver, at the census subdivision
# level, and return the associated geography files in \code{sf} format:
census_data <- get_census(dataset='CA16', regions=list(CMA="59933"),
level='CSD', geo_format = "sf")
## End(Not run)
Get identifiers for census regions intersecting a geometry
Description
This function returns a list of regions that intersect a given geometry input. This list of regions can be used
directly to query census when one is interested in census data for a particular geographic region that does
not coincide with defined census geometries. The returned value can be used as the regions
parameter in get_census to get corresponding census geographies and variables that cover the give geometry.
Input spatial objects can be any sf or sfc class objects such as POINT, MULTIPOINT or POLYGON.
This function comes with CensusMapper API limits
Usage
get_intersecting_geometries(
dataset,
level,
geometry,
simplified = FALSE,
use_cache = TRUE,
quiet = FALSE,
api_key = Sys.getenv("CM_API_KEY")
)
Arguments
dataset |
A CensusMapper dataset identifier. |
level |
The census aggregation level to retrieve. One of |
geometry |
A valid |
simplified |
If |
use_cache |
If set to |
quiet |
When TRUE, suppress messages and warnings. |
api_key |
An API key for the CensusMapper API. Defaults to |
Source
Census data and boundary geographies are reproduced and distributed on an "as is" basis with the permission of Statistics Canada (Statistics Canada 1996; 2001; 2006; 2011; 2016).
Examples
## Not run:
# Example using a POINT-class object from a pair of lat/lon coordinates
point_geo <- sf::st_sfc(sf::st_point(c(-123.25149, 49.27026)), crs=4326)
regions <- get_intersecting_geometries(dataset = 'CA16', level = 'CT', geometry = point_geo)
census_data <- get_census(dataset='CA16', regions=regions,
vectors=c("v_CA16_408","v_CA16_409","v_CA16_410"),
level='CT')
# Example using a POLYGON-class object from a bounding box with four coordinates
poly_geo <- sf::st_as_sfc(sf::st_bbox(c(ymin = 49.25, ymax = 49.30,
xmin = -123.25, xmax = -123.30)), crs = 4326)
regions <- get_intersecting_geometries(dataset = 'CA16', level = 'CT', geometry = poly_geo)
census_data <- get_census(dataset='CA16', regions=regions,
vectors=c("v_CA16_408","v_CA16_409","v_CA16_410"), level='CT')
## End(Not run)
Get metadata for recalled data
Description
Grabs recall data from server if needed and returns list of recalled data
Usage
get_recalled_database(refresh = FALSE, warn_only_once = FALSE)
Arguments
refresh |
Will force refresh of recalled database |
warn_only_once |
Will only warn on first run, 'FALSE' by default |
Value
tibble with rows describing recalled data
Examples
## Not run:
get_recalled_database()
## End(Not run)
Read GeoSuite tables
Description
Reads a table of the Statistics Canada GeoSuite for the given census year. The GeoSuite has a table for
each geographic level, with the codes and names of the areas, how they relate to other levels, population
and dwelling counts, land areas and representative points, along with code tables like the census
subdivision types. Called without level this lists the tables available for the census year.
The data comes from parquet files hosted under https://data.mountainmath.ca/census/geo_suite/,
as Statistics Canada now blocks programmatic downloads of the GeoSuite. The files are derived from
Statistics Canada data under the Statistics Canada Open Licence. They get downloaded on first use and
cached if the cancensus cache path has been set, and cached copies only get updated with
refresh = TRUE. Reading the tables requires the duckdb and DBI packages.
Usage
get_statcan_geo_suite(
level = NULL,
census_year = "2021",
refresh = FALSE,
language = getOption("cancensus.language", "en"),
quiet = FALSE
)
Arguments
level |
the table to read, e.g. |
census_year |
census year to get the data for, one of 1996, 2001, 2006, 2011, 2016 or 2021. For
older censuses |
refresh |
(logical) download the table again if true, and report if it has changed |
language |
language of the column labels and table titles, one of |
quiet |
(logical) suppress messages and the progress bar if |
Value
tibble with the GeoSuite table, with a description of each column in its "label" attribute.
The "metadata" attribute of the tibble holds the metadata of the table, including the attribution,
licence, source and notes. If level is NULL, a tibble with the table names, their title and
primary_key and the size of the file in bytes. If the data can't be downloaded this gives a warning,
and returns the cached data when refreshing existing cached data and NULL otherwise.
Tables and columns
The GeoSuite is available for the censuses from 1996 to 2021. The tables differ between census years,
for example 1996 has enumeration areas (EA) instead of dissemination areas and blocks, 2001 to 2006 have
urban areas (UA) and 2011 on population centres (POPCTR). Tables ending in _P hold the parts of
areas that span provinces or other areas. PN is the place name table, called LOC in the source.
Column names follow the attribute files from get_statcan_geographic_attributes(): the level, the
measure and the census year, e.g. CSDUID, CSDPOP2021 or DARPLAT. The same columns have the same
names across census years, and the tables can be joined to the attribute files without renaming. A suffix
A marks counts of the previous census adjusted to the current boundaries, and C or AC corrected
counts from the count review. Columns referring to other levels hold the code within the parent
level as in the source, e.g. CSDCODE instead of CSDUID. Each column has a description in its
"label" attribute, and the Statistics Canada field name in the source_field entry of the columns
metadata.
Examples
## Not run:
# list the tables of the 2021 GeoSuite
get_statcan_geo_suite(census_year = "2021")
# read the dissemination areas
get_statcan_geo_suite("DA", "2021")
## End(Not run)
Read the Geographic Attributes File
Description
Reads the geographic attributes for the given census year, with one row for each area of the lowest census geography. The table contains the information on how all the geographic levels are related for each area, along with population and dwelling counts and representative points.
The data comes from parquet files hosted under https://data.mountainmath.ca/census/geo_attributes/,
as Statistics Canada now blocks programmatic downloads of these files. The files are derived from
Statistics Canada data under the Statistics Canada Open Licence. They get downloaded on first use and
cached if the cancensus cache path has been set, and cached copies only get updated with
refresh = TRUE. Reading the files requires the duckdb and DBI packages.
A reference guide for the 2021 file is available at https://www150.statcan.gc.ca/n1/en/catalogue/92-151-G2021001
Usage
get_statcan_geographic_attributes(
census_year = "2021",
refresh = FALSE,
language = getOption("cancensus.language", "en"),
quiet = FALSE
)
Arguments
census_year |
census year to get the data for, one of 1981, 1986, 1991, 1996, 2001, 2006, 2011, 2016 or 2021 |
refresh |
(logical) download the file again if true, and report if it has changed |
language |
language of the column labels, one of |
quiet |
(logical) suppress messages and the progress bar if |
Value
tibble with the attribute data, with a description of each column in its "label" attribute.
The "metadata" attribute of the tibble holds the metadata of the file, including the attribution,
licence, source and notes. If the file can't be downloaded this gives a warning, and returns the cached
data when refreshing existing cached data and NULL otherwise.
Differences between census years
Column names follow the 2021 file, but the available columns differ between census years. The main change is between 1996 and 2001:
2001 to 2021 have one row per dissemination block, identified by
DBUID. There is no 2001 attribute file, the 2001 data was derived from the 2001 GeoSuite and has no total dwelling counts or block areas.1981 to 1996 have one row per enumeration area, identified by
EAUID. These have different columns, for exampleCTCODEinstead ofCTUIDand no dissemination areas.
Identifiers are only unique within a census year, the same DBUID or EAUID in another year
does not generally refer to the same area. In 2001 and 2006 the fields for census metropolitan areas and
agglomerations, census tracts and urban areas were filled outside of those areas to match the files from
2011 on, so not all of these values are in the source. The notes_en entry of the metadata has details
on this and on any problems with the source of each file.
Examples
# read the attributes for the 2021 census
## Not run:
attributes <- get_statcan_geographic_attributes("2021")
# where the data comes from
attr(attributes, "metadata")$attribution_en
## End(Not run)
Read geographic boundary data from StatCan
Description
Reads the original unprocessed geographic boundary files from Statistics Canada
Usage
get_statcan_geographies(
census_year,
level,
type = "cartographic",
cache_path = NULL,
timeout = 1000,
refresh = FALSE,
quiet = FALSE,
precision = "detailed"
)
Arguments
census_year |
census year to get the data for, "2021" or "2026". Not all 2026 boundary files are available yet, Statistics Canada plans to release those for "CMACA", "CT", "POPCNTR" and "DPL" on February 10, 2027, and for "FSA" on September 28, 2027. |
level |
geographic level to return the data for, valid choices are "PR","CD","CMACA","CSD","CT","ADA","DA","DB","ER","FED","DPL","POPCNTR", "FSA", "HR", and for 2026 also "CAR" (census agricultural regions) and "CCS" (census consolidated subdivisions) |
type |
type of geographic data, valid choices area "cartographic" or "digital" |
cache_path |
optional path to cache the data. If the cancensus cache path is set the geographic data gets cached in the "geographies" subdirectory of the cancensus cache path. |
timeout |
optional timeout parameter, adjust as needed if the data download times out when using slow connections |
refresh |
(logical) refresh the cache if true |
quiet |
(logical) suppress messages if 'TRUE' |
precision |
precision of cartographic boundary files, "detailed" (the default) or "generalized". Generalized boundary files are new with the 2026 census and are only available for 'type = "cartographic"'. They are simplified for mapping at smaller scales while keeping the shape of and the spatial relationships between the geographic areas. |
Value
a spatial dataframe with the geographic data. Statistics Canada blocks plain downloads of these files with a browser verification. If the safeconduct package is installed and finds Google Chrome or another Chromium-based browser, the download goes through that browser, set 'options(cancensus.use_browser = FALSE)' to turn this off. Otherwise, or if that fails, this gives a warning explaining how to download the file manually, and returns the cached data when refreshing existing cached data and 'NULL' otherwise
Examples
# get the digital geographic boundaries for provinces and territories
## Not run:
get_statcan_geographies(census_year="2021",level="PR",type="digital")
# generalized cartographic boundaries of 2026 census divisions
get_statcan_geographies(census_year="2026",level="CD",precision="generalized")
## End(Not run)
Read the Dissemination Geographies Relationship File (deprecated)
Description
This function is deprecated and will be removed in a future release, as Statistics Canada blocks
programmatic downloads of the file (#228). Use get_statcan_geographic_attributes("2021") instead, which
has the same DGUIDs for each dissemination block apart from census agricultural regions, along with the
IDs, names and counts, and covers the censuses back to 1981.
Unlike the relationship file, the attribute file fills CMADGUID outside census metropolitan areas and
census agglomerations with the metropolitan influenced zone, and CTDGUID outside areas with census tracts
with a placeholder census tract. CMATYPE %in% c("B", "D", "K") selects the blocks in census metropolitan
areas and census agglomerations. Census agricultural regions (CARDGUID) are only in the relationship file,
which can still be downloaded manually from Statistics Canada.
Reads the Dissemination Geographies Relationship File for the given census year. The table contains the information on how all the geographic levels are related for each area. Data gets cached after first download if the cancensus cache path has been set. A reference guide is available at https://www150.statcan.gc.ca/n1/en/catalogue/982600032021001
Usage
get_statcan_geography_relationships(census_year = "2021", refresh = FALSE)
Arguments
census_year |
census year to get the data for, "2021" or "2026". The 2026 file doesn't have the
census metropolitan areas and census agglomerations, census tracts, population centres and designated
places yet, Statistics Canada plans to release these geographies on February 10, 2027. Use
|
refresh |
(logical) refresh the cache if true |
Value
tibble with the relationship data. If Statistics Canada blocks the download, it goes through
a browser with the safeconduct package where that is installed and finds Google Chrome or another
Chromium-based browser, as for get_statcan_geographies(). Otherwise, or if that fails, this gives a
warning explaining how to download the file manually, and returns the cached data when
refreshing existing cached data and NULL otherwise
Examples
## Not run:
# use the attribute file instead
attributes <- get_statcan_geographic_attributes("2021")
## End(Not run)
Query the StatCan WDS for data
Description
Get official census data from Statistics Canada for a given set of DGUIDs. Only available for the 2021 census. The downloaded data gets enriched by geographic and characteristic names based on metadata obtained via 'get_statcan_wds_metadata()'. Data is cached for the duration of the R session.
Usage
get_statcan_wds_data(
DGUIDs,
members = NULL,
version = NULL,
gender = "All",
language = "en",
refresh = FALSE
)
Arguments
DGUIDs |
census year to get the data for, right now only 2021 is supported. Valid DGUIDs for a given geographic level can be queried via 'get_statcan_wds_metadata()'. |
members |
list of Member IOs to download data for. By default all characteristics are downloaded. Valid Member IDs and their descriptions can be queried via the 'get_statcan_wds_metadata()' call. |
version |
optionally specify a version of the data to download. For example, for FED level data, version 1.3 will access the 2013 represenation order, whereas version 2.0 will access the 2023 representation order. By default the latest available version is accessed. |
gender |
optionally query data for only one gender. By default this queries data for all genders, possible values are "Total", "Male", "Female" to only query total data, or for males only or for females only. |
language |
specify language for geography and characteristic names that get added, valid choices are "en" and "fr" |
refresh |
default is 'FALSE' will refresh the temporary cache if 'TRUE' |
Value
tibble with the enriched census data
Examples
# get data for federal electoral district 2013A000459021
## Not run:
get_statcan_wds_data(DGUIDs="2013A000459021",level="FED")
## End(Not run)
Query the StatCan WDS for metadata
Description
Get official metadata information from Statistics Canada for a given geographic level. Only available for the 2021 census. Data is cached for the duration of the R session.
Usage
get_statcan_wds_metadata(census_year, level, version = NULL, refresh = FALSE)
Arguments
census_year |
census year to get the data for, right now only 2021 is supported |
level |
geographic level to return the data for, valid choices are "PR","CD","CMACA","CSD","CT","ADA","DA","ER","FED","DPL","POPCNTR", "FSA", "HR" |
version |
optionally specify a version of the data to download. For example, for FED level data, version 1.3 will access the 2013 represenation order, whereas version 2.0 will access the 2023 representation order. By default the latest available version is accessed. |
refresh |
default is 'FALSE' will refresh the temporary cache if 'TRUE' |
Value
tibble with the metadata
Examples
# get metadata for federal electoral districts
## Not run:
get_statcan_wds_metadata(census_year="2021",level="FED")
## End(Not run)
Return Census variable names and labels as a tidy data frame
Description
Return Census variable names and labels as a tidy data frame
Usage
label_vectors(x)
Arguments
x |
A data frame, |
Value
A data frame with a column variable containing the truncated
variable name, and a column label describing it.
Examples
## Not run:
# Query census data with truncated labels:
label_data <- get_census(dataset='CA16', regions=list(CMA="59933"),
vectors=c("v_CA16_408","v_CA16_409","v_CA16_410"),
level='CSD', geo_format = "sf", labels="short")
# Get details for truncated vectors:
label_vectors(label_data)
## End(Not run)
List cached files
Description
Lists all cached data and metadata if available
Usage
list_cancensus_cache()
Value
tibble with metadata on cached data
Examples
# list add the cached census data
list_cancensus_cache()
Query the CensusMapper API for available datasets.
Description
Query the CensusMapper API for available datasets.
Usage
list_census_datasets(use_cache = TRUE, quiet = FALSE)
Arguments
use_cache |
If set to TRUE (the default), data will be read from a temporary local cache for the duration of the R session, if available. If set to FALSE, query the API for the data, and refresh the temporary cache with the result. |
quiet |
When TRUE, suppress messages and warnings. |
Value
Returns a data frame with a column dataset containing the code for the
dataset, a column description describing it, a geo_dataset column
identifying the geography dataset the data is based on, a attribution column
with an attribution string, a reference column with a reference identifier, and
a reference_url column with a link to reference materials.
Examples
# List available datasets in CensusMapper
## Not run:
list_census_datasets()
## End(Not run)
Query the CensusMapper API for available regions in a given dataset.
Description
Query the CensusMapper API for available regions in a given dataset.
Usage
list_census_regions(dataset, use_cache = TRUE, quiet = FALSE)
Arguments
dataset |
The dataset to query for available regions, e.g.
|
use_cache |
If set to TRUE (the default), data will be read from a local cache that is maintained for the duration of the R session, if available. If set to FALSE, query the API for the data, and refresh the local cache with the result. |
quiet |
When TRUE, suppress messages and warnings. |
Value
Returns a data frame with the following columns:
regionThe region identifier.
nameThe name of that region.
levelThe census aggregation level of that region.
popThe population of that region.
municipal_statusAdditional identifiers to distinguish the municipal status of census subdivisions.
CMA_UIDThe identifier for the Census Metropolitan Area the region is in (if any).
CD_UIDThe identifier for the Census District the region is in (if any).
PR_UIDThe identifier for the Province the region is in (if unique).
Examples
## Not run:
list_census_regions('CA16')
## End(Not run)
Query the CensusMapper API for available vectors for a given dataset.
Description
Query the CensusMapper API for available vectors for a given dataset.
Usage
list_census_vectors(
dataset,
use_cache = TRUE,
quiet = TRUE,
language = getOption("cancensus.language", "en")
)
Arguments
dataset |
The dataset to query for available vectors, e.g.
|
use_cache |
If set to TRUE (the default), data will be read from a local cache that is maintained for the duration of the R session, if available. If set to FALSE, query the API for the data, and refresh the local cache with the result. |
quiet |
When FALSE, shows messages and warnings. Set to TRUE by default. |
language |
Language of the |
Value
Returns a data frame detailing the available Census vectors (i.e. variables) for a given Census
dataset. This data frame has columns vector containing the short code for the
variable, type describing whether it's a female, male, or total aggregate, label
indicating the name of the variable, units indicating whether the value represents a
numeric integer, percentage, dollar figure, or ratio, parent_vector to show hierarchical
relationship, aggregation indicating whether the value is additive or a transformation,
and a column details with a detailed description of the variable generated by traversing
all labels within its hierarchical structure.
Examples
## Not run:
# List all vectors for a given Census dataset in CensusMapper
list_census_vectors('CA16')
# The same list with French labels
list_census_vectors('CA16', language = 'fr')
## End(Not run)
List recalled data stored in local cache
Description
Checks the local cached database for recalled data and lists all recalled cached entries
Usage
list_recalled_cached_data(
cached_data = list_cancensus_cache(),
warn_only_once = FALSE
)
Arguments
cached_data |
List of locally cached data to check for recall, default is 'list_cancensus_cache()' in which case it will get checked against all locally cached data |
warn_only_once |
Will only warn on first run during each session, 'FALSE' by default |
Value
tibble with rows describing locally cached recalled data
Examples
## Not run:
list_recalled_cached_data()
## End(Not run)
List all parent variables from vector hierarchies given either a list of Census
variables returned by
list_census_vectors, search_census_vectors, find_census_vectors, or a direct string reference to the vector code.
Description
List all parent variables from vector hierarchies given either a list of Census
variables returned by
list_census_vectors, search_census_vectors, find_census_vectors, or a direct string reference to the vector code.
Usage
parent_census_vectors(vector_list, language = NULL)
Arguments
vector_list |
The list of vectors to be used, either a character vector or a filtered tibble
as returned from |
language |
Language of the labels, one of |
Examples
# Query parent vectors directly using vector identifier
parent_census_vectors("v_CA16_2519")
## Not run:
# Example using multiple vectors coerced into a list
parent_census_vectors(c("v_CA16_2519","v_CA16_2520","v_CA16_2521"))
# or, equivalently
selected_vectors <- c("v_CA16_2519","v_CA16_2520","v_CA16_2521")
parent_census_vectors(selected_vectors)
# Example using dplyr and piped arguments
library(dplyr, warn.conflicts = FALSE)
list_census_vectors("CA16") %>%
filter(vector == "v_CA16_2519") %>%
parent_census_vectors()
## End(Not run)
Remove cached files
Description
Remove cached data for paths given
Usage
remove_from_cancensus_cache(paths)
Arguments
paths |
list of paths to remove, as returned by the path column in 'list_cancensus_cache' |
Value
freed-up disk space
Examples
## Not run:
# remove the first cached dataset
cache_data <- list_cancensus_cache()
remove_from_cancensus_cache(cache_data$path[1])
## End(Not run)
Remove recalled data from local cache
Description
Checks the local cached database for recalled data and removes cached data that has been recalled
Usage
remove_recalled_cached_data()
Value
Storage size of removed locally cached data that got freed up in number of bytes.
Examples
## Not run:
remove_recalled_cached_data()
## End(Not run)
Make an API call, retrying on transient failures
Description
Retries with exponential backoff, honouring a 'Retry-After' header of up to 60 seconds. Responses saying the server is busy (HTTP 503 or 429) get retried up to 'max(retries, busy_retries)' times, other transient HTTP errors (408, 502, 504) and network errors up to 'retries' times. Other responses, including other server errors, are returned as they are.
Usage
retry_api_call(
call_fn,
retries = 0,
busy_retries = 2,
quiet = FALSE,
language = NULL
)
Arguments
call_fn |
Function making the request and returning an httr response |
retries |
Number of further attempts on transient failures |
busy_retries |
Minimum number of further attempts when the server is busy |
quiet |
Whether to suppress messages about retries. Waits of more than 2 seconds for a busy server are always reported. |
language |
Language of the messages, see |
Value
The last httr response
Binned colour scale for choropleth maps, as on CensusMapper
Description
A discrete fill (or colour) scale for numeric values that bins them at
breaks and colours the bins from a palette, with legend labels for
the bins formatted for the kind of values shown. Values below the first
break go in the first bin and values at or above the last break in the
last, as in CensusMapper's maps. It extends ggplot2::scale_fill_manual():
values sets the colours directly and labels the legend labels.
Usage
scale_fill_cm_bins(
palette = "Blues",
breaks = NULL,
n = 5,
direction = 1,
units = c("number", "percentage", "percentage_100", "ratio", "currency",
"currency_1000"),
language = getOption("cancensus.language", "en"),
values = NULL,
labels = NULL,
na.value = "grey60",
...,
aesthetics = "fill"
)
scale_colour_cm_bins(..., aesthetics = "colour")
Arguments
palette |
The palette the colours come from: the name of a ColorBrewer
palette (e.g. |
breaks |
The cutoffs between the bins, in increasing order. By default
|
n |
The number of bins when there are no |
direction |
1 for the palette's colours in their order, -1 for the reverse. |
units |
What the values are, for formatting the labels:
|
language |
Language for formatting the labels, |
values |
Colours for the bins, from the lowest to the highest, instead of the palette's. |
labels |
Labels for the bins instead of the ones made from
|
na.value |
The colour for missing values. |
... |
Other arguments passed on to |
aesthetics |
The aesthetics the scale works with, e.g.
|
Details
The legend shows every bin in its colour, including bins without data. If
you pass your own guide, add override.aes = list(.draw = TRUE)
to it, or show.legend = TRUE to the layer, to keep this with
ggplot2 3.5 or later.
Value
A ggplot2 scale.
Examples
## Not run:
library(ggplot2)
census_data <- get_census("CA21", regions = list(CMA = "59933"),
vectors = c(lim_at = "v_CA21_1085"),
level = "CT", geo_format = "sf")
ggplot(census_data) +
geom_sf(aes(fill = lim_at / 100), colour = NA) +
scale_fill_cm_bins(palette = "YlOrRd", breaks = c(0.05, 0.1, 0.15, 0.2),
units = "percentage") +
coord_sf(datum = NA)
## End(Not run)
Query the CensusMapper API for regions with names matching a searchterm.
Description
Runs a query against the CensusMapper API to retrieve region data with
names matching specific queries. Users can optionally specify the target geography level
(e.g. level = 'CMA', level = 'CSD', etc.). Alternatively, calling
explore_census_vectors() will launch the interactive region selection tool on
the CensusMapper site in a new web page or tab.
Usage
search_census_regions(searchterm, dataset, level = NA, ...)
Arguments
searchterm |
The term to search for e.g. |
dataset |
The dataset to query for available regions, e.g.
|
level |
One of |
... |
Further arguments passed on to |
Value
A census region list of the same format as 'list_census_regions()' containing the matches.
Examples
## Not run:
# This will return a warning that no match was found, but will suggest similar named regions.
search_census_regions('Victorea', 'CA16')
# This will limit region results to only include CMA level regions
search_census_regions('Victoria', 'CA16', level = "CMA")
## End(Not run)
Query the CensusMapper API for vectors with descriptions matching a search term or phrase (deprecated)
Description
Query the CensusMapper API for vectors with descriptions matching a search term or phrase (deprecated)
Usage
search_census_vectors(searchterm, dataset, type = NA, ...)
Arguments
searchterm |
The term or phrase to search for e.g. |
dataset |
The dataset to query for available vectors, e.g.
|
type |
One of |
... |
Further arguments passed on to |
Examples
## Not run:
search_census_vectors('Ojibway', 'CA16')
# This will return a warning that no match was found, but will suggest similar terms.
search_census_vectors('Ojibwe', 'CA16', 'Total')
## End(Not run)
Set Censusmapper API key
Description
Cancensus requires a free Censusmapper API key to retrieve data. This function helps set the key for either the duration of the session (default) or permanently for use across sessions.
Usage
set_cancensus_api_key(key, overwrite = FALSE, install = FALSE)
Arguments
key |
a Censusmapper API key. For more information on keys see the API key section |
overwrite |
Option to overwrite any existing Censusmapper keys already stored locally. |
install |
Option to install permanently for use across sessions. |
Examples
## Not run:
set_cancensus_api_key("YOUR_CM_API_KEY")
# This will set the key permanently until overwritten again
set_cancensus_api_key("YOUR_CM_API_KEY", install = TRUE)
## End(Not run)
Set cancensus cache location
Description
Cancensus caches retrieved data to increase speeds and reduce API usage. By default the cache only lasts for the R session. This function sets a cache location that persists across sessions, either for all projects or for a specific project.
Usage
set_cancensus_cache_path(cache_path, overwrite = FALSE, install = FALSE)
Arguments
cache_path |
a local directory to use for saving cached data |
overwrite |
Option to overwrite any existing cache path already stored in |
install |
Option to install permanently for use across sessions and projects. |
Details
With install = TRUE the cache path is added to your .Renviron file and is used across sessions
and projects.
With install = FALSE the cache path applies to the current R session, taking precedence over one
stored in .Renviron. Calling this at the top of a script gives a project its own cache, for example to
back up the data together with the project for reproducibility. All cache functions, like
list_cancensus_cache() and remove_recalled_cached_data(), then work on this project cache.
Use an absolute path, for example via
here::here(). Relative paths get resolved against the working directory at the time of use, which can differ e.g. when knitting a document.Set the path before the first call to
get_census(). The check of the whole cache for recalled data only runs once per session, data read from a cache set later only gets checked as it is read.Don't set the cache path in a project-level
.Renvironfile unless it also has your API key. R reads a project-level.Renvironfile instead of the one in your home directory, not in addition to it.
The cache path is stored in the CM_CACHE_PATH environment variable. The older
cancensus.cache_path option is still supported, but is only used if the environment variable is not set.
Examples
## Not run:
# This will set the cache path for the current session, for example for a project-specific cache
set_cancensus_cache_path("~/my_project/cancensus_cache")
# This will set the cache path permanently until overwritten again
set_cancensus_cache_path("~/cancensus_cache", install = TRUE)
## End(Not run)
View saved Censusmapper API key
Description
View saved API key'
Usage
show_cancensus_api_key()
Examples
## Not run:
show_cancensus_api_key()
## End(Not run)
View saved cache directory path
Description
View the cache path in use, from the CM_CACHE_PATH environment variable or
otherwise the cancensus.cache_path option.
Usage
show_cancensus_cache_path()
Value
The cache path, or NULL with a message if none is set
Examples
## Not run:
show_cancensus_cache_path()
## End(Not run)
Visualize Census vector hierarchies as ASCII tree
Description
Displays an ASCII tree representation of the hierarchical structure of Census vectors. This helps users understand the relationship between parent and child vectors when selecting variables for their analysis.
Usage
visualize_vector_hierarchy(
vector,
dataset = NULL,
max_depth = NA,
show_type = FALSE,
quiet = FALSE,
language = NULL
)
Arguments
vector |
A Census vector code (e.g., "v_CA16_2510") or a filtered tibble
as returned from |
dataset |
The dataset to query for vector information, e.g. |
max_depth |
Maximum depth of the tree to display. Default is |
show_type |
Logical. If |
quiet |
When |
language |
Language of the labels, one of |
Value
Invisibly returns a tibble of the vectors displayed in the tree. The tree is printed to the console as a side effect.
Examples
## Not run:
# Visualize the age hierarchy for 2016 Census
visualize_vector_hierarchy("v_CA16_2510", dataset = "CA16")
# Show only first two levels with type information
visualize_vector_hierarchy("v_CA16_2510", dataset = "CA16",
max_depth = 2, show_type = TRUE)
# Using a vector tibble from list_census_vectors
library(dplyr)
list_census_vectors("CA16") %>%
filter(vector == "v_CA16_2510") %>%
visualize_vector_hierarchy()
## End(Not run)