Last active
April 3, 2024 14:13
-
-
Save rcatlord/becdd21c67ddef4fbcf71c429cdcabaf to your computer and use it in GitHub Desktop.
Median age by local authority
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Median age by local authority | |
# Source: 2021 Census | |
# URL: https://www.nomisweb.co.uk/datasets/c2021ts007 | |
library(tidyverse) ; library(nomisr) ; library(sf) ; library(tmap) | |
# return Topic Summary tables | |
metadata <- nomis_search(name = "TS*") | |
# filter Topic Summary tables containing 'Age' | |
metadata |> | |
filter(str_detect(name.value, 'Age')) |> | |
select(id, name.value) | |
# return geographies for 'Age by single year' table | |
nomis_get_metadata(id = "NM_2027_1", | |
concept = "GEOGRAPHY", | |
type = "type") | |
# get data | |
request <- nomis_get_data(id = "NM_2027_1", | |
time = c("latest"), | |
geography = "TYPE154") | |
# calculate median age | |
df <- request |> | |
filter(MEASURES_NAME == "Value", | |
str_detect(C2021_AGE_102_CODE, "_")) |> | |
select(areacd = GEOGRAPHY_CODE, | |
age = C2021_AGE_102, | |
n = OBS_VALUE) |> | |
group_by(areacd, age) |> | |
summarise(n) |> | |
summarise(median_age = age[max(which(cumsum(n)/sum(n) <= 0.5))]) | |
# Local authority boundaries (2021) | |
# Source: ONS Open Geography Portal | |
# URL: https://geoportal.statistics.gov.uk/datasets/ons::local-authority-districts-december-2021-gb-buc-1 | |
lad <- read_sf("Local_Authority_Districts_December_2021_GB_BUC_2022_1023427260691650215.geojson") |> | |
filter(!str_detect(LAD21CD, "^S")) |> | |
select(areacd = LAD21CD, areanm = LAD21NM) |> | |
st_transform(4326) | |
# join tabular data to spatial layer | |
sf <- left_join(lad, df, by = "areacd") | |
# plot results | |
tmap_mode("view") | |
tm_shape(sf) + | |
tmap_options(check.and.fix = TRUE) + | |
tm_fill(col = "median_age", | |
style = "jenks", | |
palette = c("#e1fcf8", "#9ccad5", "#5e99af", "#136a85", "#003b55"), | |
alpha = 0.7, | |
colorNA = "grey50", | |
id = "areanm", | |
popup.vars = c("Median age (2021):" = "median_age"), | |
title = "Median age (years), 2021") + | |
tm_borders(col = "#000000") + | |
tm_layout(title = "Age structure of the population, 2021<br><span style='font-weight: normal;'>Local authorities in England and Wales</span><br><span style='font-weight: normal; font-size: 0.875em;'>Source: 2021 Census</span>") | |
# export results | |
tmap_last() %>% | |
tmap_save("index.html") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment