pkgs <- c("tidyverse", "cansim", "cancensus",
"sf", "tmap", "readxl", "writexl")
devtools::update_packages(pkgs, dep = TRUE) # update install
pkgs2 <- c(pkgs, "foreign", "here") # included in Base R
inst = lapply(pkgs2, library, character.only = TRUE) # load them
options(cansim.cache_path = here(".data-raw"))
options(cancensus.api_key='YOUR CANADA CENSUS API COMES HERE')
options(cancensus.cache_path = here(".data-raw"))
References
# 01. create a list of CD/CSD ----
# list_cansim_tables(refresh=TRUE) # run once in a while; this may take a minute.
list_full <- list_census_vectors(dataset = 'CA16')
region_toronto <- list_census_regions(dataset = "CA16") %>%
filter(region %in% c("3521", "3519", "3520", "3518")) %>%
as_census_region_list()
region_vancouver <- list_census_regions(dataset = "CA16") %>%
filter(region %in% c("5915022", "5915015", "5915025", "5915055", "5915046", "5915051",
"5915029", "5915034", "5915043", "5915036", "5915038", "5915004",
"5915011", "5915802")) %>% # plus V6T V6S
as_census_region_list()
# 02. import shapefile into R as sf ----
lcd <- st_read(".data-raw/lcd_000b16a_e.shp") # Census divisions
lcsd <- st_read(".data-raw/lcsd000b16a_e.shp") # Census subdivisions
lfsa <- st_read(".data-raw/lfsa000b16a_e.shp") # Forward Sortation Areas
# 03. create a list of zipcodes ----
lcd_toronto <- lcd %>% filter(CDUID %in% region_toronto[[1]])
lcsd_vancouver <- lcsd %>% filter(CSDUID %in% region_vancouver[[1]])
lfas_pt <- lfsa %>% st_centroid(of_largest_polygon = TRUE)
lfas_toronto <- lfas_pt[lcd_toronto, ]
lfas_vancouver <- lfas_pt[lcsd_vancouver, ]
tmap_mode("view")
Vancouver
# 04. draw maps ----
lfsa %>%
filter(CFSAUID %in% lfas_vancouver$CFSAUID) %>%
tm_shape() +
tm_borders(col = "white", lwd = 1) +
tm_fill(col= "blue", alpha = 0.3) +
tm_text("CFSAUID", size = 0.8) +
tm_shape(lcsd_vancouver) +
tm_borders(col = "white", lwd = 1) +
tm_fill(col= "red", alpha = 0.3) +
tm_text("CSDNAME", size = 1, col = "black")
Toronto
lfsa %>%
filter(CFSAUID %in% lfas_toronto$CFSAUID) %>%
tm_shape() +
tm_borders(col = "white", lwd = 1) +
tm_fill(col= "blue", alpha = 0.3) +
tm_text("CFSAUID", size = 0.8) +
tm_shape(lcd_toronto) +
tm_borders(col = "red") +
tm_fill(col= "red", alpha = 0.3) +
tm_text("CDNAME", size = 1, col = "black")
# 05. export as an .xlsx ----
as_tibble(lfas_toronto) %>%
rbind(as_tibble(lfas_vancouver)) %>%
mutate(metro = ifelse(PRNAME == "Ontario", "Toronto", "Vancouver")) %>%
select(metro, CFSA = CFSAUID) %>%
write_xlsx(".data-final/cfsa_Canada.xlsx")