| Type: | Package |
| Title: | Access, Retrieve, and Work with Canadian Census Data and Geography |
| Version: | 0.6.2 |
| 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). |
| 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, leaflet, mapdeck, rmarkdown, scales, sp, 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-19 15:32:12 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-19 16:40:16 UTC |
A dataset with code table summaries for census data
Description
A dataset with code table summaries for census data
Author(s)
derived from StatCan definitions
References
https://www12.statcan.gc.ca/census-recensement/2021/geo/ref/domain-domaine/index2021-eng.cfm?lang=e&id=CSDtype, https://www12.statcan.gc.ca/census-recensement/2021/geo/ref/domain-domaine/index2021-eng.cfm?lang=e&id=CDtype
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)
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 |
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()
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 the geosuite data
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
)
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","DB,"ER","FED","DPL","POPCNTR", "FSA", "HR" |
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' |
Value
a spatial dataframe with the geographic data. If Statistics Canada blocks the download 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")
## End(Not run)
Read the Dissemination Geographies Relationship File (deprecated)
Description
This function is deprecated and will be removed in the next 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, only 2021 is available |
refresh |
(logical) refresh the cache if true |
Value
tibble with the relationship data. If Statistics Canada blocks the download 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
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)