4  Introduction to the cancensus package

The cancensus R package (von Bergmann, Shkolnik, and Jacobs 2022) interfaces with the CensusMapper API server. It can be queried for

A slight complication, the cancensus package needs an API key. You can sign up for one for free on CensusMapper.

Once you have your API key it’s useful to store it as an environment variable in your .Renviron configuration file so it’s available in all your R sessions.

Code
install.packages("cancensus")

cancensus::set_api_key(key = "CensusMapper_XXXX...XXXX", install=TRUE)

By default {cancensus} caches downloaded census data, which makes it easier and faster to re-run analysis and protects from overusing the CensusMapper API quota. To use caching a local path needs to be designated for data caching. The cache is shared across R sessions.

Code
cancensus::set_cache_path(cache_path = "<local path of cache data>", install=TRUE)

{cancensus} provides convenient access to census data. Calls to {cancensus} require to spectify

As an example we will retrieve the share of the population in Toronto, Mississauga, and Brampton spending 30% or more of income on shelter costs in 2016.

Code
library(cancensus)
library(dplyr)
regions <- list(CSD=c("3520005","3521005","3521010"))
vectors <- c(shelter_cost_burdened="v_CA16_4889", shelter_base = "v_CA16_4886")

data <- get_census(dataset = "CA16", regions=regions, vectors=vectors)
data %>% 
  mutate(`Share shelter cost burdened`=shelter_cost_burdened/shelter_base) |>
  select(GeoUID,`Region Name`,`Share shelter cost burdened`)
# A tibble: 3 × 3
  GeoUID  `Region Name`    `Share shelter cost burdened`
  <chr>   <fct>                                    <dbl>
1 3520005 Toronto (C)                              0.296
2 3521005 Mississauga (CY)                         0.264
3 3521010 Brampton (CY)                            0.305