Skip to content

Instantly share code, notes, and snippets.

@USMortality
Created December 26, 2024 16:11
Show Gist options
  • Save USMortality/6ae352c324d665c7b75bcafae944f094 to your computer and use it in GitHub Desktop.
Save USMortality/6ae352c324d665c7b75bcafae944f094 to your computer and use it in GitHub Desktop.
Norway Adult Deaths & Population, 2021-2023
library(readr)
library(tidyr)
library(readxl)
library(tidyverse)
### Deaths
# https://ec.europa.eu/eurostat/databrowser/product/view/demo_magec
df <- read_tsv("/Users/Ben/Downloads/estat_demo_magec.tsv")
cleaned_data <- df |>
separate(
col = 1, # First column of the dataset
into = c("freq", "unit", "sex", "age", "geo"),
sep = ",", # Assuming values are separated by commas
remove = TRUE
)
# Filtering and selecting columns as needed
filtered_data <- cleaned_data |>
filter(geo == "NO", sex == "T") |>
select(freq, unit, sex, age, geo, `2021`, `2022`) |>
mutate(
# Extract numeric age or handle special cases
age_numeric = case_when(
age == "TOTAL" ~ NA_real_, # Set TOTAL to NA
age == "UNK" ~ NA_real_, # Set UNK to NA
age == "Y_LT1" ~ 0, # Less than 1 year old mapped to 0
age == "Y_OPEN" ~ 100, # 100+ mapped to 100
TRUE ~ as.numeric(str_remove(age, "^Y")) # Remove "Y" and convert to num
)
) |>
filter(
age_numeric >= 18 # Select ages 18+ or rows with NA (e.g., TOTAL)
) |>
select(-age_numeric)
# 2023 not avail; thus double '22
sum(as.integer(filtered_data$`2021`)) + 2 * sum(as.integer(filtered_data$`2022`))
### Population
# https://www.ssb.no/en/statbank/table/07459/tableViewLayout1/
# Ages 0-105+
pop <- read_xlsx("/Users/ben/Downloads/population.xlsx", skip = 3) |>
filter(!is.na(`2021`)) |>
setNames(c("age", "2021", "2022", "2023")) |>
mutate(
age = str_replace_all(str_replace_all(age, " years", ""), " year", ""),
age = case_when(
age == "105 or older" ~ "105+",
TRUE ~ age
)
)
a <- pop |> filter(!age %in% as.character(0:17))
(sum(a$`2021`) + sum(a$`2022`) + sum(a$`2023`)) / 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment