Skip to content

Instantly share code, notes, and snippets.

@dakvid
Created November 2, 2021 08:41
Show Gist options
  • Save dakvid/739b5e6accf86dc6f266ecf4de51dc78 to your computer and use it in GitHub Desktop.
Save dakvid/739b5e6accf86dc6f266ecf4de51dc78 to your computer and use it in GitHub Desktop.
Process NZ population data into grid points from SA2s
# Create a bubble grid of New Zealand population using
# data for Statistical Areas 2
# For #30DayMapChallenge day 1 - points
# -- David Friggens, November 2021
library(readr)
library(sf)
# Get the centroids for SA2s
# From https://datafinder.stats.govt.nz
# There are various flavours on offer, and different download options
# I chose Geopackage :-)
geo_sa2 <-
read_sf("statistical-area-2-2021-centroid-inside.gpkg") %>%
select(area_code = SA22021_V1_00,
area_name = SA22021_V1_00_NAME,
lat = LATITUDE,
lon = LONGITUDE,
geom)
# Get population for SA2s
# From https://nzdotstat.stats.govt.nz
# Again various output options - need to select to have code in
# the output as well as names; I chose "CSV" with tab separator
pop_sa2 <-
read_tsv("population.tsv",
col_types = "cccccciii") %>%
filter(YEAR == 2021L) %>%
select(area_code = AREA,
population = `Value Flags`)
# Join them together, round lat/lon to 1dp and sum
corners <-
geo_sa2 %>%
transmute(area_code,
lat = round(lat, 1),
lon = round(lon, 1)) %>%
st_drop_geometry() %>%
inner_join(pop_sa2) %>%
group_by(lat, lon) %>%
summarise(population = sum(population)) %>%
ungroup() %>%
filter(population > 0)
write_csv(corners, "population_corners.csv")
# # If you want to plot in R
# library(purrr)
# corners_geo <-
# corners %>%
# mutate(geom =
# list(lon, lat) %>%
# transpose() %>%
# map(unlist) %>%
# map(st_point)) %>%
# st_as_sf()
#
# library(ggplot)
# ggplot(corners_g) +
# geom_sf(aes(size = population),
# alpha = 0.4,
# show.legend = FALSE) +
# coord_sf(datum = NA)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment