Post

Reconstructing a Published Table

Which districts had the largest population changes from 2019 to 2023? In the textbook’s synthetic report, each district line gives several annual counts, but the region name appears only once for a block of districts. Some district names occur in more than one region. Comparing the same place across years therefore requires recovering relationships expressed by the report’s layout.

We reconstruct district records by distinguishing data from headings and totals, assigning regions and years, and matching regional identifiers. We then compare the reconstructed sums with the report’s published totals before calculating changes. The final comparison ranks gains and losses by their absolute size and distinguishes that ranking from percentage change and national population share.

24.1 Separating table structure from observations

In data/raw/public/population_cp1252.csv, Seoul’s subtotal already includes Jongno-gu. Adding both lines would count Jongno-gu’s residents twice. Reading the file one line at a time shows where the region is named and where each district’s population is recorded.

The report uses Windows-1252, so each byte in this file decodes to one character. readr::read_lines() with locale(encoding = "windows-1252") and Python’s bytes.decode("windows-1252") decode the text. Each line in this file ends with one newline character. The R character total adds one character per line because read_lines() removes the newline separators. A matching character count alone cannot verify the encoding: two single-byte encodings can give the same count. The example therefore also checks the en dash in the title and the dagger in the footnote.

1
2
3
4
5
6
7
8
9
10
11
library(tidyverse)

population_path <- "data/raw/public/population_cp1252.csv"
source_bytes <- readBin(population_path, "raw", n = file.size(population_path))
lines <- read_lines(population_path, locale = locale(encoding = "windows-1252"))
c(
  bytes = length(source_bytes),
  lines = length(lines),
  characters = sum(nchar(lines)) + length(lines)
)
c(dash = utf8ToInt(lines[1])[41], dagger = utf8ToInt(lines[251])[1])
1
2
3
4
     bytes      lines characters 
     15445        251      15445 
  dash dagger 
  8211   8224 
1
2
3
4
5
6
7
8
9
10
from pathlib import Path

import polars as pl

population_path = Path("data/raw/public/population_cp1252.csv")
source_bytes = population_path.read_bytes()
text = source_bytes.decode("windows-1252")
lines = text.splitlines()
{"bytes": len(source_bytes), "lines": len(lines), "characters": len(text)}
(hex(ord(lines[0][40])), hex(ord(lines[-1][0])))
1
2
{'bytes': 15445, 'lines': 251, 'characters': 15445}
('0x2013', '0x2020')

Lines with fixed positions

The 15,445-byte file contains 251 lines. The character codes show an en dash, U+2013, in the title and a dagger, U+2020, at the start of the footnote. The numbered excerpt shows where the district counts begin and which lines describe the table.

1
2
excerpt_lines <- c(1:6, 251)
writeLines(paste(excerpt_lines, lines[excerpt_lines]))
1
2
3
4
5
6
7
1 "Registered population by district, 2019–2023 (synthetic data for this textbook)",,,,,,
2 Province,District,2019,2020,2021,2022,2023
3 ,,Total population (persons),Total population (persons),Total population (persons),Total population (persons),Total population (persons)
4 Nationwide,Total,"51,052,236","51,082,752","51,157,486","51,229,421","51,299,993"
5 Seoul,Subtotal,"9,924,388","9,900,388","9,875,346","9,844,752","9,819,920"
6 ,Jongno-gu,"440,154","437,997","439,663","438,216","437,036"
251 † These figures are synthetic data made for this textbook.,,,,,,
1
2
3
excerpt_lines = [1, 2, 3, 4, 5, 6, 251]
for number in excerpt_lines:
    print(number, lines[number - 1])
1
2
3
4
5
6
7
1 "Registered population by district, 2019–2023 (synthetic data for this textbook)",,,,,,
2 Province,District,2019,2020,2021,2022,2023
3 ,,Total population (persons),Total population (persons),Total population (persons),Total population (persons),Total population (persons)
4 Nationwide,Total,"51,052,236","51,082,752","51,157,486","51,229,421","51,299,993"
5 Seoul,Subtotal,"9,924,388","9,900,388","9,875,346","9,844,752","9,819,920"
6 ,Jongno-gu,"440,154","437,997","439,663","438,216","437,036"
251 † These figures are synthetic data made for this textbook.,,,,,,

Rows inside the table

Lines 1 to 3 give the title, the column names, and the unit for all five years, persons; the last line is a footnote. These lines describe how to read the table. In the header, Province names regions such as Seoul and Busan, and District names their districts. The table body begins on line 4 with Nationwide,Total, the national population against which we can check the sum of the district counts.

Within the table body, a region name followed by Subtotal opens a regional block. The district lines below it have an empty region field: Jongno-gu belongs to Seoul because it follows the Seoul subtotal. The line number identifies each source record, while a block number connects each district to the subtotal that names its region. Classifying lines by role and numbering the regional blocks will make those relationships explicit.

The totals also contain commas inside quoted values, such as "51,299,993". Those commas are thousands separators, while commas outside quotation marks separate fields. A split at every comma treats the commas in "51,299,993" as field boundaries too. The last three pieces returned by stringr::str_split_1() and the Python string method split() show what becomes of that one count.

1
2
3
pieces <- str_split_1(lines[4], ",")
length(pieces)
tail(pieces, 3)
1
2
[1] 17
[1] "\"51"  "299"   "993\""
1
2
3
pieces = lines[3].split(",")
len(pieces)
pieces[-3:]
1
2
17
['"51', '299', '993"']

The naive split returns 17 pieces for seven fields. It breaks the final count into "51, 299, and 993", with the quotation marks at opposite ends. A CSV reader must first recover the intact fields.

readr::read_csv() applies the quoting rule and the stated encoding. With field names given and every type set to character, headers and counts alike are read as text. na = "" recognizes the empty region cells, and trim_ws = FALSE preserves spaces at field edges.

After import, row_number() records the source line before case_when() assigns its role. The positional tests handle the title, headers, and footnote before the content tests classify totals, subtotals, and districts. cumsum(role == "province subtotal") counts subtotals as it proceeds, so a subtotal and the districts below it share a block number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
field_names <- paste0("field_", 1:7)
source_rows <- read_csv(
  population_path,
  col_names = field_names,
  col_types = cols(.default = col_character()),
  na = "",
  trim_ws = FALSE,
  locale = locale(encoding = "windows-1252")
) |>
  mutate(line = row_number(), .before = 1) |>
  mutate(
    role = case_when(
      line == 1 ~ "title",
      line == 2 ~ "variable header",
      line == 3 ~ "descriptive header",
      line == n() ~ "footnote",
      field_2 == "Total" ~ "national total",
      field_2 == "Subtotal" ~ "province subtotal",
      is.na(field_1) ~ "district",
      .default = "unclassified"
    ),
    block = cumsum(role == "province subtotal")
  )
dim(source_rows)
source_rows |>
  filter(line %in% c(4:6, 30:32)) |>
  select(line, role, block, field_1, field_2, field_7)
1
2
3
4
5
6
7
8
9
10
[1] 251  10
# A tibble: 6 × 6
   line role              block field_1    field_2     field_7   
  <int> <chr>             <int> <chr>      <chr>       <chr>     
1     4 national total        0 Nationwide Total       51,299,993
2     5 province subtotal     1 Seoul      Subtotal    9,819,920 
3     6 district              1 <NA>       Jongno-gu   437,036   
4    30 district              1 <NA>       Gangdong-gu 547,315   
5    31 province subtotal     2 Busan      Subtotal    4,149,666 
6    32 district              2 <NA>       Jung-gu     147,067   

In Polars, pl.read_csv() decodes Windows-1252 and respects quoted commas. has_header=False reads the headers as records, new_columns sets the seven field names, and infer_schema=False reads every field as text.

with_row_index("line", offset=1) records the source positions before the pl.when() chain assigns positional roles and then tests the fields. A second with_columns() computes block from the newly created role, because expressions within one call cannot use each other’s new columns. cum_sum() counts the subtotals encountered so far, assigning a subtotal and its following districts to the same block.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
field_names = ["field_" + str(number) for number in range(1, 8)]
source_rows = (
    pl.read_csv(
        population_path,
        has_header=False,
        new_columns=field_names,
        infer_schema=False,
        encoding="windows-1252",
    )
    .with_row_index("line", offset=1)
    .with_columns(
        role=pl.when(pl.col("line") == 1)
        .then(pl.lit("title"))
        .when(pl.col("line") == 2)
        .then(pl.lit("variable header"))
        .when(pl.col("line") == 3)
        .then(pl.lit("descriptive header"))
        .when(pl.col("line") == len(lines))
        .then(pl.lit("footnote"))
        .when(pl.col("field_2") == "Total")
        .then(pl.lit("national total"))
        .when(pl.col("field_2") == "Subtotal")
        .then(pl.lit("province subtotal"))
        .when(pl.col("field_1").is_null())
        .then(pl.lit("district"))
        .otherwise(pl.lit("unclassified"))
    )
    .with_columns(block=(pl.col("role") == "province subtotal").cum_sum())
)
source_rows.shape
source_rows.filter(pl.col("line") == 4)["field_7"].item()
source_rows.filter(pl.col("line").is_in([4, 5, 6, 30, 31, 32])).select(
    "line", "role", "block", "field_1", "field_2", "field_7"
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(251, 10)
'51,299,993'
shape: (6, 6)
┌──────┬───────────────────┬───────┬────────────┬─────────────┬────────────┐
│ line ┆ role              ┆ block ┆ field_1    ┆ field_2     ┆ field_7    │
│ ---  ┆ ---               ┆ ---   ┆ ---        ┆ ---         ┆ ---        │
│ u32  ┆ str               ┆ u32   ┆ str        ┆ str         ┆ str        │
╞══════╪═══════════════════╪═══════╪════════════╪═════════════╪════════════╡
│ 4    ┆ national total    ┆ 0     ┆ Nationwide ┆ Total       ┆ 51,299,993 │
│ 5    ┆ province subtotal ┆ 1     ┆ Seoul      ┆ Subtotal    ┆ 9,819,920  │
│ 6    ┆ district          ┆ 1     ┆ null       ┆ Jongno-gu   ┆ 437,036    │
│ 30   ┆ district          ┆ 1     ┆ null       ┆ Gangdong-gu ┆ 547,315    │
│ 31   ┆ province subtotal ┆ 2     ┆ Busan      ┆ Subtotal    ┆ 4,149,666  │
│ 32   ┆ district          ┆ 2     ┆ null       ┆ Jung-gu     ┆ 147,067    │
└──────┴───────────────────┴───────┴────────────┴─────────────┴────────────┘

In the classified excerpt, 51,299,993 is one field. Jongno-gu and Gangdong-gu share block 1 with Seoul. The Jung-gu on line 32 shares block 2 with Busan. The counts below show whether any line is unclassified or any district appears before the first regional subtotal.

1
2
3
4
5
6
7
8
9
10
count(source_rows, role)
c(
  lines = nrow(source_rows),
  distinct_lines = n_distinct(source_rows$line),
  unclassified = sum(source_rows$role == "unclassified"),
  references = sum(source_rows$role %in% c("national total", "province subtotal")),
  districts = sum(source_rows$role == "district"),
  district_blocks = n_distinct(source_rows$block[source_rows$role == "district"]),
  outside_blocks = sum(source_rows$role == "district" & source_rows$block == 0)
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# A tibble: 7 × 2
  role                   n
  <chr>              <int>
1 descriptive header     1
2 district             229
3 footnote               1
4 national total         1
5 province subtotal     17
6 title                  1
7 variable header        1
          lines  distinct_lines    unclassified      references       districts 
            251             251               0              18             229 
district_blocks  outside_blocks 
             17               0 
1
2
3
4
5
6
7
8
9
10
11
12
13
source_rows.group_by("role").agg(n=pl.len()).sort("role")
district_rows = source_rows.filter(pl.col("role") == "district")
{
    "lines": source_rows.height,
    "distinct_lines": source_rows["line"].n_unique(),
    "unclassified": (source_rows["role"] == "unclassified").sum(),
    "references": source_rows["role"]
    .is_in(["national total", "province subtotal"])
    .sum(),
    "districts": district_rows.height,
    "district_blocks": district_rows["block"].n_unique(),
    "outside_blocks": (district_rows["block"] == 0).sum(),
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
shape: (7, 2)
┌────────────────────┬─────┐
│ role               ┆ n   │
│ ---                ┆ --- │
│ str                ┆ u32 │
╞════════════════════╪═════╡
│ descriptive header ┆ 1   │
│ district           ┆ 229 │
│ footnote           ┆ 1   │
│ national total     ┆ 1   │
│ province subtotal  ┆ 17  │
│ title              ┆ 1   │
│ variable header    ┆ 1   │
└────────────────────┴─────┘
{'lines': 251, 'distinct_lines': 251, 'unclassified': 0, 'references': 18, 'districts': 229, 'district_blocks': 17, 'outside_blocks': 0}

The 251 lines include 229 district lines, 17 regional subtotals, and one national total. Every district falls inside a regional block. Its subtotal names the region and gives five annual totals against which we can check the district sums.

24.2 Recovering district records and repeated years

Line 32 names Jung-gu and gives 147,067 in its last column. Which region’s Jung-gu does that count describe, and for which year? Line 31 names Busan. Its districts occupy lines 32 to 47, just above the Daegu subtotal. The header on line 2 identifies the last column as 2023.

In R, mutate() places the subtotal’s field_1 value in province, with NA elsewhere. fill(province, .by = block, .direction = "down") copies that value down within each block. Block 0 has no subtotal and receives no label. The last block contains the footnote, so the final if_else() removes labels from all lines except subtotals and districts. At lines 30 through 33, the subtotal on line 31 marks the change from one region to the next.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
labeled_rows <- source_rows |>
  mutate(province = if_else(role == "province subtotal", field_1, NA)) |>
  fill(province, .by = block, .direction = "down") |>
  mutate(
    province = if_else(role %in% c("province subtotal", "district"), province, NA)
  )
source_rows |>
  filter(line %in% 30:33) |>
  select(line, role, block, field_1, field_2)
labeled_rows |>
  filter(line %in% 30:33) |>
  select(line, role, block, province, field_2)
districts <- filter(labeled_rows, role == "district")
references <- filter(labeled_rows, role %in% c("national total", "province subtotal"))
c(
  districts = nrow(districts),
  references = nrow(references),
  without_province = sum(is.na(districts$province)),
  footnote_with_province = sum(
    labeled_rows$role == "footnote" & !is.na(labeled_rows$province)
  )
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# A tibble: 4 × 5
   line role              block field_1 field_2    
  <int> <chr>             <int> <chr>   <chr>      
1    30 district              1 <NA>    Gangdong-gu
2    31 province subtotal     2 Busan   Subtotal   
3    32 district              2 <NA>    Jung-gu    
4    33 district              2 <NA>    Seo-gu     
# A tibble: 4 × 5
   line role              block province field_2    
  <int> <chr>             <int> <chr>    <chr>      
1    30 district              1 Seoul    Gangdong-gu
2    31 province subtotal     2 Busan    Subtotal   
3    32 district              2 Busan    Jung-gu    
4    33 district              2 Busan    Seo-gu     
             districts             references       without_province 
                   229                     18                      0 
footnote_with_province 
                     0 

Gangdong-gu is labeled Seoul, and the Busan subtotal gives the label for Jung-gu and Seo-gu. All 229 districts now have a region, while the footnote has none.

The region identifies where a count belongs; the column header identifies when. Reading line 2 pairs field_3 through field_7 with 2019 through 2023. unlist() turns the header row into a character vector of years, and set_names() attaches those years as names to the field names. The named vector year_fields lets select() rename those columns by year. parse_count() sets the comma as the grouping mark, and across() applies it to each year column.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
year_fields <- field_names[3:7]
years <- source_rows |>
  filter(line == 2) |>
  select(all_of(year_fields)) |>
  unlist(use.names = FALSE)
year_fields <- set_names(year_fields, years)
year_fields
parse_count <- \(x) parse_number(x, locale = locale(grouping_mark = ","))
district_counts <- districts |>
  select(line, province, district = field_2, all_of(year_fields)) |>
  mutate(across(all_of(years), parse_count))
districts |>
  filter(line == 32) |>
  select(line, field_2, field_7)
district_counts |>
  filter(line == 32) |>
  select(line, district, `2023`)
c(
  missing = sum(is.na(select(district_counts, all_of(years)))),
  smallest = min(select(district_counts, all_of(years)))
)
1
2
3
4
5
6
7
8
9
10
11
12
     2019      2020      2021      2022      2023 
"field_3" "field_4" "field_5" "field_6" "field_7" 
# A tibble: 1 × 3
   line field_2 field_7
  <int> <chr>   <chr>  
1    32 Jung-gu 147,067
# A tibble: 1 × 3
   line district `2023`
  <int> <chr>     <dbl>
1    32 Jung-gu  147067
 missing smallest 
       0    16608 

On line 32, the recorded text 147,067 becomes the number 147067 under 2023. The original string remains available in districts, and the five numeric columns have no missing counts.

To compare annual values, we need one row per district and year. pivot_longer() puts the year names in year and the counts in population, repeating line, province, and district. Each resulting row should identify one district in one year and lead back to one cell in the report. The code checks both descriptions by counting distinct combinations of region, district, and year, then distinct combinations of source line and year.

1
2
3
4
5
6
7
8
9
10
district_years <- district_counts |>
  pivot_longer(all_of(years), names_to = "year", values_to = "population") |>
  mutate(year = as.integer(year))
filter(district_years, province == "Busan", district == "Jung-gu")
c(
  rows = nrow(district_years),
  keys = n_distinct(district_years$province, district_years$district,
                    district_years$year),
  sources = n_distinct(district_years$line, district_years$year)
)
1
2
3
4
5
6
7
8
9
10
# A tibble: 5 × 5
   line province district  year population
  <int> <chr>    <chr>    <int>      <dbl>
1    32 Busan    Jung-gu   2019     152557
2    32 Busan    Jung-gu   2020     150774
3    32 Busan    Jung-gu   2021     149079
4    32 Busan    Jung-gu   2022     148156
5    32 Busan    Jung-gu   2023     147067
   rows    keys sources 
   1145    1145    1145 

In Polars, pl.when() places field_1 on subtotal lines and null elsewhere. forward_fill().over("block") copies the label down only within its regional block. The footnote lies in the last block and would receive that block’s label, so the second with_columns() restricts labels to subtotals and districts. The display shows the Ulsan block before the two roles are separated into districts and references.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
labeled_rows = source_rows.with_columns(
    province=pl.when(pl.col("role") == "province subtotal")
    .then(pl.col("field_1"))
    .forward_fill()
    .over("block")
).with_columns(
    province=pl.when(pl.col("role").is_in(["province subtotal", "district"])).then(
        pl.col("province")
    )
)
labeled_rows.filter(pl.col("block") == 7).select(
    "line", "role", "block", "province", "field_2"
)
districts = labeled_rows.filter(pl.col("role") == "district")
references = labeled_rows.filter(
    pl.col("role").is_in(["national total", "province subtotal"])
)
{
    "districts": districts.height,
    "references": references.height,
    "without_province": districts["province"].null_count(),
    "footnote_with_province": labeled_rows.filter(pl.col("role") == "footnote")[
        "province"
    ]
    .is_not_null()
    .sum(),
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
shape: (6, 5)
┌──────┬───────────────────┬───────┬──────────┬──────────┐
│ line ┆ role              ┆ block ┆ province ┆ field_2  │
│ ---  ┆ ---               ┆ ---   ┆ ---      ┆ ---      │
│ u32  ┆ str               ┆ u32   ┆ str      ┆ str      │
╞══════╪═══════════════════╪═══════╪══════════╪══════════╡
│ 81   ┆ province subtotal ┆ 7     ┆ Ulsan    ┆ Subtotal │
│ 82   ┆ district          ┆ 7     ┆ Ulsan    ┆ Jung-gu  │
│ 83   ┆ district          ┆ 7     ┆ Ulsan    ┆ Nam-gu   │
│ 84   ┆ district          ┆ 7     ┆ Ulsan    ┆ Dong-gu  │
│ 85   ┆ district          ┆ 7     ┆ Ulsan    ┆ Buk-gu   │
│ 86   ┆ district          ┆ 7     ┆ Ulsan    ┆ Ulju-gun │
└──────┴───────────────────┴───────┴──────────┴──────────┘
{'districts': 229, 'references': 18, 'without_province': 0, 'footnote_with_province': 0}

Ulsan’s five districts now have the region label written on line 81. Four of their names occur in other regions, so that label is part of their identity.

The region identifies where a count belongs; the column header identifies when. row(0, named=True) reads the variable header as a dictionary, and year_fields pairs the field names with their recorded years. Each expression in year_counts removes the commas, which are known here to be thousands separators, and casts the remaining digits to pl.Int64. In the call to select(), **year_counts passes each dictionary entry as a named argument, so each key, such as 2019, becomes the name of the resulting column.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
header = source_rows.filter(pl.col("line") == 2).row(0, named=True)
year_fields = {field: header[field] for field in field_names[2:]}
year_fields
years = list(year_fields.values())
year_counts = {
    year: pl.col(field).str.replace_all(",", "", literal=True).cast(pl.Int64)
    for field, year in year_fields.items()
}
district_counts = districts.select(
    "line", "province", district="field_2", **year_counts
)
districts.filter(pl.col("line") == 32).select("line", "field_2", "field_7")
district_counts.filter(pl.col("line") == 32).select("line", "district", "2023")
{
    "missing": district_counts.select(years).null_count().sum_horizontal().item(),
    "smallest": district_counts.select(years).min().min_horizontal().item(),
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{'field_3': '2019', 'field_4': '2020', 'field_5': '2021', 'field_6': '2022', 'field_7': '2023'}
shape: (1, 3)
┌──────┬─────────┬─────────┐
│ line ┆ field_2 ┆ field_7 │
│ ---  ┆ ---     ┆ ---     │
│ u32  ┆ str     ┆ str     │
╞══════╪═════════╪═════════╡
│ 32   ┆ Jung-gu ┆ 147,067 │
└──────┴─────────┴─────────┘
shape: (1, 3)
┌──────┬──────────┬────────┐
│ line ┆ district ┆ 2023   │
│ ---  ┆ ---      ┆ ---    │
│ u32  ┆ str      ┆ i64    │
╞══════╪══════════╪════════╡
│ 32   ┆ Jung-gu  ┆ 147067 │
└──────┴──────────┴────────┘
{'missing': 0, 'smallest': 16608}

On line 32, 147,067 becomes 147067, and no annual count is null. To represent each district and year on a separate row, unpivot() repeats line, province, and district for each year. The five rows for Busan’s Jung-gu all point to line 32; the year column, cast to pl.Int32, identifies which of its five counts each row contains. Counting the distinct district-year and source-cell combinations checks that the reshaping preserves both identities.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
district_years = district_counts.unpivot(
    on=years,
    index=["line", "province", "district"],
    variable_name="year",
    value_name="population",
).with_columns(pl.col("year").cast(pl.Int32))
district_years.filter(
    (pl.col("province") == "Busan") & (pl.col("district") == "Jung-gu")
).sort("year")
{
    "rows": district_years.height,
    "keys": district_years.select("province", "district", "year").n_unique(),
    "sources": district_years.select("line", "year").n_unique(),
}
1
2
3
4
5
6
7
8
9
10
11
12
13
shape: (5, 5)
┌──────┬──────────┬──────────┬──────┬────────────┐
│ line ┆ province ┆ district ┆ year ┆ population │
│ ---  ┆ ---      ┆ ---      ┆ ---  ┆ ---        │
│ u32  ┆ str      ┆ str      ┆ i32  ┆ i64        │
╞══════╪══════════╪══════════╪══════╪════════════╡
│ 32   ┆ Busan    ┆ Jung-gu  ┆ 2019 ┆ 152557     │
│ 32   ┆ Busan    ┆ Jung-gu  ┆ 2020 ┆ 150774     │
│ 32   ┆ Busan    ┆ Jung-gu  ┆ 2021 ┆ 149079     │
│ 32   ┆ Busan    ┆ Jung-gu  ┆ 2022 ┆ 148156     │
│ 32   ┆ Busan    ┆ Jung-gu  ┆ 2023 ┆ 147067     │
└──────┴──────────┴──────────┴──────┴────────────┘
{'rows': 1145, 'keys': 1145, 'sources': 1145}

Reference totals by year

Each of the 1,145 rows identifies one district in one year and corresponds to a different cell in the report. The published totals use the same year columns. Reshaping them separately gives us figures to check against the district sums for each year.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
reference_years <- references |>
  select(line, role, label = field_1, all_of(year_fields)) |>
  mutate(across(all_of(years), parse_count)) |>
  pivot_longer(all_of(years), names_to = "year", values_to = "reference") |>
  mutate(year = as.integer(year))
national_references <- reference_years |>
  filter(role == "national total") |>
  select(line, year, reference)
province_references <- reference_years |>
  filter(role == "province subtotal") |>
  select(line, province = label, year, reference)
national_references
c(
  province_rows = nrow(province_references),
  province_keys = n_distinct(province_references$province, province_references$year),
  shared_lines = length(intersect(district_years$line, reference_years$line))
)
1
2
3
4
5
6
7
8
9
10
# A tibble: 5 × 3
   line  year reference
  <int> <int>     <dbl>
1     4  2019  51052236
2     4  2020  51082752
3     4  2021  51157486
4     4  2022  51229421
5     4  2023  51299993
province_rows province_keys  shared_lines 
           85            85             0 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
reference_years = (
    references.select("line", "role", label="field_1", **year_counts)
    .unpivot(
        on=years,
        index=["line", "role", "label"],
        variable_name="year",
        value_name="reference",
    )
    .with_columns(pl.col("year").cast(pl.Int32))
)
national_references = (
    reference_years.filter(pl.col("role") == "national total")
    .select("line", "year", "reference")
    .sort("year")
)
province_references = reference_years.filter(
    pl.col("role") == "province subtotal"
).select("line", "year", "reference", province="label")
national_references
{
    "province_rows": province_references.height,
    "province_keys": province_references.select("province", "year").n_unique(),
    "shared_lines": len(
        set(district_years["line"].to_list()) & set(reference_years["line"].to_list())
    ),
}
1
2
3
4
5
6
7
8
9
10
11
12
13
shape: (5, 3)
┌──────┬──────┬───────────┐
│ line ┆ year ┆ reference │
│ ---  ┆ ---  ┆ ---       │
│ u32  ┆ i32  ┆ i64       │
╞══════╪══════╪═══════════╡
│ 4    ┆ 2019 ┆ 51052236  │
│ 4    ┆ 2020 ┆ 51082752  │
│ 4    ┆ 2021 ┆ 51157486  │
│ 4    ┆ 2022 ┆ 51229421  │
│ 4    ┆ 2023 ┆ 51299993  │
└──────┴──────┴───────────┘
{'province_rows': 85, 'province_keys': 85, 'shared_lines': 0}

The reference tables contain five national totals and 85 regional totals, with no source lines shared with the districts. These totals can therefore be compared with district sums without being included in them. For Busan’s Jung-gu, the 2023 count and the region name come from two different source lines. Its block number connects them.

1
2
3
4
5
6
7
8
9
10
11
12
district_years |>
  filter(line == 32, year == 2023) |>
  left_join(select(source_rows, line, block, source_text = field_7), by = join_by(line))
references |>
  filter(block == 2) |>
  select(line, role, block, province)
c(
  districts = n_distinct(district_years$province, district_years$district),
  district_names = n_distinct(district_years$district),
  long_rows = nrow(district_years),
  years_per_district = unique(count(district_years, line)$n)
)
1
2
3
4
5
6
7
8
9
10
# A tibble: 1 × 7
   line province district  year population block source_text
  <int> <chr>    <chr>    <int>      <dbl> <int> <chr>      
1    32 Busan    Jung-gu   2023     147067     2 147,067    
# A tibble: 1 × 4
   line role              block province
  <int> <chr>             <int> <chr>   
1    31 province subtotal     2 Busan   
         districts     district_names          long_rows years_per_district 
               229                207               1145                  5 
1
2
3
4
5
6
7
8
9
10
11
12
13
district_years.filter((pl.col("line") == 32) & (pl.col("year") == 2023)).join(
    source_rows.select("line", "block", source_text="field_7"), on="line", how="left"
)
references.filter(pl.col("block") == 2).select("line", "role", "block", "province")
{
    "districts": district_years.select("province", "district").n_unique(),
    "district_names": district_years["district"].n_unique(),
    "long_rows": district_years.height,
    "years_per_district": district_years.group_by("line")
    .agg(n=pl.len())["n"]
    .unique()
    .to_list(),
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
shape: (1, 7)
┌──────┬──────────┬──────────┬──────┬────────────┬───────┬─────────────┐
│ line ┆ province ┆ district ┆ year ┆ population ┆ block ┆ source_text │
│ ---  ┆ ---      ┆ ---      ┆ ---  ┆ ---        ┆ ---   ┆ ---         │
│ u32  ┆ str      ┆ str      ┆ i32  ┆ i64        ┆ u32   ┆ str         │
╞══════╪══════════╪══════════╪══════╪════════════╪═══════╪═════════════╡
│ 32   ┆ Busan    ┆ Jung-gu  ┆ 2023 ┆ 147067     ┆ 2     ┆ 147,067     │
└──────┴──────────┴──────────┴──────┴────────────┴───────┴─────────────┘
shape: (1, 4)
┌──────┬───────────────────┬───────┬──────────┐
│ line ┆ role              ┆ block ┆ province │
│ ---  ┆ ---               ┆ ---   ┆ ---      │
│ u32  ┆ str               ┆ u32   ┆ str      │
╞══════╪═══════════════════╪═══════╪══════════╡
│ 31   ┆ province subtotal ┆ 2     ┆ Busan    │
└──────┴───────────────────┴───────┴──────────┘
{'districts': 229, 'district_names': 207, 'long_rows': 1145, 'years_per_district': [5]}

For Jung-gu, field 7 on line 32 gives the 2023 count, 147,067. Line 31 names Busan for block 2. All 229 districts have five annual counts, yet only 207 names are distinct. Matching the codes will require both region and district.

24.3 Matching regional identifiers with composite keys

The region and district names identify which rows belong together. The workbook data/raw/public/region_codes.xlsx supplies a district code for each such pair, so we can use the code to match annual counts. Its Codes sheet lets us determine which code belongs to Jung-gu in Busan.

Codes must be read as text to preserve their initial zeros. readxl::read_excel() with col_types = "text" requests text columns explicitly. The workbook also stores the codes as text, so pl.read_excel() with engine="openpyxl" reads a code such as 02001 with its initial zero.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
library(readxl)
codes_path <- "data/raw/public/region_codes.xlsx"
excel_sheets(codes_path)
codes <- read_excel(codes_path, sheet = "Codes", col_types = "text")
filter(codes, `District name` == "Jung-gu")
district_pairs <- distinct(district_years, province, district)
c(
  population_pairs = nrow(district_pairs),
  population_names = n_distinct(district_pairs$district),
  repeated_names = sum(count(district_pairs, district)$n > 1),
  code_rows = nrow(codes),
  code_names = n_distinct(codes$`District name`),
  code_pairs = n_distinct(codes$`Province name`, codes$`District name`)
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[1] "Codes"
# A tibble: 6 × 4
  `Province code` `Province name` `District code` `District name`
  <chr>           <chr>           <chr>           <chr>          
1 01              Seoul           01002           Jung-gu        
2 02              Busan           02001           Jung-gu        
3 03              Daegu           03001           Jung-gu        
4 04              Incheon         04001           Jung-gu        
5 06              Daejeon         06002           Jung-gu        
6 07              Ulsan           07001           Jung-gu        
population_pairs population_names   repeated_names        code_rows 
             229              207                7              229 
      code_names       code_pairs 
             207              229 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
codes_path = "data/raw/public/region_codes.xlsx"
codes = pl.read_excel(codes_path, sheet_name="Codes", engine="openpyxl")
codes.filter(pl.col("District name") == "Jung-gu")
district_pairs = district_years.select("province", "district").unique()
{
    "population_pairs": district_pairs.height,
    "population_names": district_pairs["district"].n_unique(),
    "repeated_names": district_pairs.group_by("district")
    .agg(n=pl.len())
    .filter(pl.col("n") > 1)
    .height,
    "code_rows": codes.height,
    "code_names": codes["District name"].n_unique(),
    "code_pairs": codes.select("Province name", "District name").n_unique(),
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
shape: (6, 4)
┌───────────────┬───────────────┬───────────────┬───────────────┐
│ Province code ┆ Province name ┆ District code ┆ District name │
│ ---           ┆ ---           ┆ ---           ┆ ---           │
│ str           ┆ str           ┆ str           ┆ str           │
╞═══════════════╪═══════════════╪═══════════════╪═══════════════╡
│ 01            ┆ Seoul         ┆ 01002         ┆ Jung-gu       │
│ 02            ┆ Busan         ┆ 02001         ┆ Jung-gu       │
│ 03            ┆ Daegu         ┆ 03001         ┆ Jung-gu       │
│ 04            ┆ Incheon       ┆ 04001         ┆ Jung-gu       │
│ 06            ┆ Daejeon       ┆ 06002         ┆ Jung-gu       │
│ 07            ┆ Ulsan         ┆ 07001         ┆ Jung-gu       │
└───────────────┴───────────────┴───────────────┴───────────────┘
{'population_pairs': 229, 'population_names': 207, 'repeated_names': 7, 'code_rows': 229, 'code_names': 207, 'code_pairs': 229}

Two labels that do not match

Busan’s Jung-gu has code 02001. Joining on Jung-gu alone would also attach the five other regions’ codes. Both files have 229 distinct pairs of region and district names, but equal counts do not establish that the pairs match. An anti join lists the workbook pairs with no exact match in the report. For the unmatched names, stringi::stri_escape_unicode() and Python’s list display reveal invisible characters as escape sequences. The character counts show whether trimming or Unicode normalization form C (NFC) removes the discrepancy.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
unmatched_codes <- anti_join(
  codes, district_pairs,
  by = join_by(`Province name` == province, `District name` == district)
) |> arrange(`Province name`)
writeLines(stringi::stri_escape_unicode(unmatched_codes$`District name`))
zwsp <- intToUtf8(0x200B)
district_pairs |>
  filter(str_trim(district, side = "right") != district) |>
  mutate(chars = nchar(district))
zero_width <- filter(codes, str_detect(`District name`, fixed(zwsp)))
writeLines(stringi::stri_escape_unicode(zero_width$`District name`))
c(
  recorded = nchar(zero_width$`District name`),
  trimmed = nchar(str_trim(zero_width$`District name`)),
  nfc = nchar(stringi::stri_trans_nfc(zero_width$`District name`))
)
1
2
3
4
5
6
7
8
9
Haeundae-gu
Chuncheon-si\u200b
# A tibble: 1 × 3
  province district       chars
  <chr>    <chr>          <int>
1 Busan    "Haeundae-gu "    12
Chuncheon-si\u200b
recorded  trimmed      nfc 
      13       13       13 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
unmatched_codes = codes.join(
    district_pairs,
    left_on=["Province name", "District name"],
    right_on=["province", "district"],
    how="anti",
).sort("Province name")
unmatched_codes["District name"].to_list()
zwsp = chr(0x200B)
district_pairs.filter(
    pl.col("district").str.strip_chars_end() != pl.col("district")
).with_columns(chars=pl.col("district").str.len_chars())
zero_width = codes.filter(pl.col("District name").str.contains(zwsp, literal=True))
zero_width["District name"].to_list()
zero_width.select(
    recorded=pl.col("District name").str.len_chars(),
    trimmed=pl.col("District name").str.strip_chars().str.len_chars(),
    nfc=pl.col("District name").str.normalize("NFC").str.len_chars(),
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
['Haeundae-gu', 'Chuncheon-si\u200b']
shape: (1, 3)
┌──────────┬──────────────┬───────┐
│ province ┆ district     ┆ chars │
│ ---      ┆ ---          ┆ ---   │
│ str      ┆ str          ┆ u32   │
╞══════════╪══════════════╪═══════╡
│ Busan    ┆ Haeundae-gu  ┆ 12    │
└──────────┴──────────────┴───────┘
['Chuncheon-si\u200b']
shape: (1, 3)
┌──────────┬─────────┬─────┐
│ recorded ┆ trimmed ┆ nfc │
│ ---      ┆ ---     ┆ --- │
│ u32      ┆ u32     ┆ u32 │
╞══════════╪═════════╪═════╡
│ 13       ┆ 13      ┆ 13  │
└──────────┴─────────┴─────┘

The population report has a trailing space after Busan’s Haeundae-gu, making it 12 characters long. In the workbook, Gangwon State’s Chuncheon-si ends in a zero-width space, U+200B. Trimming leaves U+200B in place because Unicode does not classify it as whitespace. The names with and without U+200B are also distinct under NFC: the workbook name still has 13 characters, whereas the report name has 12. The matching rule must therefore remove that specific character as well as the trailing space.

In R, match_label() removes U+200B, trims trailing whitespace, and applies NFC. mutate() adds the resulting name in district_key beside the original name. Only the two inspected labels should change. Each table should still distinguish 229 districts by region and name. In the workbook, province codes should be two characters wide and district codes five.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
count(codes, province_chars = nchar(`Province code`),
      district_chars = nchar(`District code`))
match_label <- function(label) {
  label |>
    str_remove_all(fixed(zwsp)) |>
    str_trim(side = "right") |>
    stringi::stri_trans_nfc()
}
codes_keyed <- mutate(codes, district_key = match_label(`District name`))
years_keyed <- mutate(district_years, district_key = match_label(district))
c(
  code_labels_changed = sum(codes_keyed$district_key != codes_keyed$`District name`),
  district_labels_changed = n_distinct(
    years_keyed$line[years_keyed$district_key != years_keyed$district]
  ),
  code_keys = n_distinct(codes_keyed$`Province name`, codes_keyed$district_key),
  district_keys = n_distinct(years_keyed$province, years_keyed$district_key)
)
1
2
3
4
5
6
7
8
# A tibble: 1 × 3
  province_chars district_chars     n
           <int>          <int> <int>
1              2              5   229
    code_labels_changed district_labels_changed               code_keys 
                      1                       1                     229 
          district_keys 
                    229 

One label changed in each file, and each still has 229 distinct pairs of region and district names. The join can now use region plus district_key. In left_join(), relationship = "many-to-one" permits the five annual rows of a district to share one code record, but prevents an annual row from matching multiple code records. The first anti join uses the original names and shows the two pairs that did not match. After cleaning, unmatched counts annual rows with no match and missing_codes counts rows with no district code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
recorded_by <- join_by(province == `Province name`, district == `District name`)
anti_join(district_pairs, codes, by = recorded_by)
coded_years <- left_join(
  years_keyed,
  select(codes_keyed, `Province name`, district_key, `Province code`, `District code`,
         `District name`),
  by = join_by(province == `Province name`, district_key),
  relationship = "many-to-one"
)
coded_years |>
  filter(line %in% c(40, 122), year == 2023) |>
  mutate(recorded_chars = nchar(district), code_chars = nchar(`District name`)) |>
  select(line, province, district_key, `District code`, recorded_chars, code_chars)
c(
  rows = nrow(coded_years),
  unmatched = nrow(anti_join(years_keyed, codes_keyed,
                             by = join_by(province == `Province name`, district_key))),
  missing_codes = sum(is.na(coded_years$`District code`)),
  keys = n_distinct(coded_years$province, coded_years$district, coded_years$year),
  code_years = n_distinct(coded_years$`District code`, coded_years$year)
)
1
2
3
4
5
6
7
8
9
10
11
12
# A tibble: 2 × 2
  province      district      
  <chr>         <chr>         
1 Busan         "Haeundae-gu "
2 Gangwon State "Chuncheon-si"
# A tibble: 2 × 6
   line province      district_key `District code` recorded_chars code_chars
  <int> <chr>         <chr>        <chr>                    <int>      <int>
1    40 Busan         Haeundae-gu  02009                       12         11
2   122 Gangwon State Chuncheon-si 10001                       12         13
         rows     unmatched missing_codes          keys    code_years 
         1145             0             0          1145          1145 

In Polars, codes.schema identifies the code columns as strings. The first district code is 01001, with its initial zero. match_label() removes U+200B, strips trailing whitespace, and applies NFC. with_columns() adds district_key alongside the recorded name. If cleaning merges two districts in the same region, the number of distinct region and name pairs will fall below 229.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
codes.schema
{
    "province_chars": codes["Province code"].str.len_chars().unique().to_list(),
    "district_chars": codes["District code"].str.len_chars().unique().to_list(),
    "first_codes": codes.row(0)[:3],
}


def match_label(column):
    return (
        pl.col(column)
        .str.replace_all(zwsp, "", literal=True)
        .str.strip_chars_end()
        .str.normalize("NFC")
    )


codes_keyed = codes.with_columns(district_key=match_label("District name"))
years_keyed = district_years.with_columns(district_key=match_label("district"))
{
    "code_labels_changed": (
        codes_keyed["district_key"] != codes_keyed["District name"]
    ).sum(),
    "district_labels_changed": years_keyed.filter(
        pl.col("district_key") != pl.col("district")
    )["line"].n_unique(),
    "code_keys": codes_keyed.select("Province name", "district_key").n_unique(),
    "district_keys": years_keyed.select("province", "district_key").n_unique(),
}
1
2
3
Schema({'Province code': String, 'Province name': String, 'District code': String, 'District name': String})
{'province_chars': [2], 'district_chars': [5], 'first_codes': ('01', 'Seoul', '01001')}
{'code_labels_changed': 1, 'district_labels_changed': 1, 'code_keys': 229, 'district_keys': 229}

The workbook has one row for each of the 229 districts. Each district occurs five times in the population table, once per year. The join on region and district_key uses validate="m:1" to allow at most one workbook record per annual row. The first anti join uses the original names. The counts unmatched and missing_codes use the cleaned names to check for annual rows without a match or a code. same_keys compares the sorted region, district, and year columns before and after the join.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
district_pairs.join(
    codes,
    left_on=["province", "district"],
    right_on=["Province name", "District name"],
    how="anti",
).sort("province")
code_columns = [
    "Province name", "district_key", "Province code", "District code", "District name"
]
coded_years = years_keyed.join(
    codes_keyed.select(code_columns),
    left_on=["province", "district_key"],
    right_on=["Province name", "district_key"],
    how="left",
    validate="m:1",
)
key_columns = ["province", "district", "year"]
{
    "rows": coded_years.height,
    "unmatched": years_keyed.join(
        codes_keyed,
        left_on=["province", "district_key"],
        right_on=["Province name", "district_key"],
        how="anti",
    ).height,
    "missing_codes": coded_years["District code"].null_count(),
    "same_keys": coded_years.select(key_columns)
    .sort(key_columns)
    .equals(district_years.select(key_columns).sort(key_columns)),
    "code_years": coded_years.select("District code", "year").n_unique(),
}
1
2
3
4
5
6
7
8
9
10
shape: (2, 2)
┌───────────────┬──────────────┐
│ province      ┆ district     │
│ ---           ┆ ---          │
│ str           ┆ str          │
╞═══════════════╪══════════════╡
│ Busan         ┆ Haeundae-gu  │
│ Gangwon State ┆ Chuncheon-si │
└───────────────┴──────────────┘
{'rows': 1145, 'unmatched': 0, 'missing_codes': 0, 'same_keys': True, 'code_years': 1145}

Both unmatched and missing_codes are zero. All 1,145 annual rows have a district code. Line 122 shows how the two recorded names for Chuncheon-si match.

1
2
3
4
5
6
chuncheon <- filter(coded_years, line == 122, year == 2023)
select(chuncheon, line, province, district_key, `Province code`, `District code`,
       population)
writeLines(paste(c("population label:", "code label:"),
                 stringi::stri_escape_unicode(c(chuncheon$district,
                                                chuncheon$`District name`))))
1
2
3
4
5
6
# A tibble: 1 × 6
   line province      district_key `Province code` `District code` population
  <int> <chr>         <chr>        <chr>           <chr>                <dbl>
1   122 Gangwon State Chuncheon-si 10              10001               275489
population label: Chuncheon-si
code label: Chuncheon-si\u200b
1
2
3
4
5
chuncheon = coded_years.filter((pl.col("line") == 122) & (pl.col("year") == 2023))
chuncheon.select(
    "line", "province", "district_key", "Province code", "District code", "population"
)
[chuncheon["district"].item(), chuncheon["District name"].item()]
1
2
3
4
5
6
7
8
9
shape: (1, 6)
┌──────┬───────────────┬──────────────┬───────────────┬───────────────┬────────────┐
│ line ┆ province      ┆ district_key ┆ Province code ┆ District code ┆ population │
│ ---  ┆ ---           ┆ ---          ┆ ---           ┆ ---           ┆ ---        │
│ u32  ┆ str           ┆ str          ┆ str           ┆ str           ┆ i64        │
╞══════╪═══════════════╪══════════════╪═══════════════╪═══════════════╪════════════╡
│ 122  ┆ Gangwon State ┆ Chuncheon-si ┆ 10            ┆ 10001         ┆ 275489     │
└──────┴───────────────┴──────────────┴───────────────┴───────────────┴────────────┘
['Chuncheon-si', 'Chuncheon-si\u200b']

The workbook name ends in U+200B. With Gangwon State and the cleaned name as the key, the district code for the 2023 count of 275,489 is 10001.

The Chuncheon-si example verifies one matched record. Across the full table, each district should have one distinct five-character code, and its first two characters should match the two-character region code.

1
2
3
4
5
6
7
8
9
10
11
12
c(
  matched_keys = n_distinct(coded_years$province, coded_years$district_key),
  codes = n_distinct(coded_years$`District code`),
  rows = nrow(coded_years),
  province_code_chars = unique(nchar(coded_years$`Province code`)),
  district_code_chars = unique(nchar(coded_years$`District code`)),
  leading_zero_codes = n_distinct(
    coded_years$`District code`[str_starts(coded_years$`District code`, "0")]
  ),
  prefix_mismatches = sum(str_sub(coded_years$`District code`, 1, 2) !=
                            coded_years$`Province code`)
)
1
2
3
4
       matched_keys               codes                rows province_code_chars 
                229                 229                1145                   2 
district_code_chars  leading_zero_codes   prefix_mismatches 
                  5                 107                   0 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
    "matched_keys": coded_years.select("province", "district_key").n_unique(),
    "codes": coded_years["District code"].n_unique(),
    "rows": coded_years.height,
    "province_code_chars": coded_years["Province code"]
    .str.len_chars()
    .unique()
    .to_list(),
    "district_code_chars": coded_years["District code"]
    .str.len_chars()
    .unique()
    .to_list(),
    "leading_zero_codes": coded_years.filter(
        pl.col("District code").str.starts_with("0")
    )["District code"].n_unique(),
    "prefix_mismatches": (
        coded_years["District code"].str.slice(0, 2) != coded_years["Province code"]
    ).sum(),
}
1
{'matched_keys': 229, 'codes': 229, 'rows': 1145, 'province_code_chars': [2], 'district_code_chars': [5], 'leading_zero_codes': 107, 'prefix_mismatches': 0}

All 229 districts have distinct codes, and 107 of the five-character codes start with zero. The textbook assigns these codes to identify the same districts across years. They are not official administrative codes.

24.4 Reconciling totals and describing geographical change

A district count assigned to the wrong region can still give the correct national total. Comparing each region’s district sum with its published subtotal can reveal that error. We can also compare the sum across all 229 districts with the national total for each year before calculating how many residents each district gained or lost.

In R, summarise() counts district rows and adds their populations by region and year. If any population is missing, sum(population) gives NA for that group. A full join includes every region and year in either table, and relationship = "one-to-one" rules out multiple matches. Subtracting the published subtotal gives the difference. The checks count missing sums and missing subtotals separately from nonzero differences between available figures. The national calculation repeats this comparison using year alone. These whole-number counts are small enough for the doubles from parse_number() to represent them exactly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
province_sums <- coded_years |>
  summarise(district_sum = sum(population), districts = n(), .by = c(province, year))
province_check <- province_sums |>
  full_join(province_references, by = join_by(province, year),
            relationship = "one-to-one") |>
  mutate(difference = district_sum - reference)
national_check <- coded_years |>
  summarise(district_sum = sum(population), districts = n(), .by = year) |>
  full_join(national_references, by = join_by(year), relationship = "one-to-one") |>
  mutate(difference = district_sum - reference)
national_check
c(
  province_rows = nrow(province_check),
  provinces = n_distinct(province_check$province),
  district_rows = sum(province_check$districts, na.rm = TRUE),
  without_reference = sum(is.na(province_check$reference)),
  without_sum = sum(is.na(province_check$district_sum)),
  differences = sum(province_check$difference != 0, na.rm = TRUE)
)
1
2
3
4
5
6
7
8
9
10
11
12
# A tibble: 5 × 6
   year district_sum districts  line reference difference
  <int>        <dbl>     <int> <int>     <dbl>      <dbl>
1  2019     51052236       229     4  51052236          0
2  2020     51082752       229     4  51082752          0
3  2021     51157486       229     4  51157486          0
4  2022     51229421       229     4  51229421          0
5  2023     51299993       229     4  51299993          0
    province_rows         provinces     district_rows without_reference 
               85                17              1145                 0 
      without_sum       differences 
                0                 0 

In Polars, group_by("province", "year") groups district rows for each regional subtotal. By default, sum() skips nulls. The condition in district_sum requires a population for every row in the group, so a partial sum cannot appear as a regional or national total. The full joins include keys from either table. A missing sum or reference gives a null difference and is counted separately from a disagreement between two available figures.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
district_sum = pl.when(pl.col("population").is_not_null().all()).then(
    pl.col("population").sum()
)
province_check = (
    coded_years.group_by("province", "year")
    .agg(district_sum=district_sum, districts=pl.len())
    .join(
        province_references,
        on=["province", "year"],
        how="full",
        coalesce=True,
        validate="1:1",
    )
    .with_columns(difference=pl.col("district_sum") - pl.col("reference"))
)
national_check = (
    coded_years.group_by("year")
    .agg(district_sum=district_sum, districts=pl.len())
    .join(national_references, on="year", how="full", coalesce=True, validate="1:1")
    .with_columns(difference=pl.col("district_sum") - pl.col("reference"))
    .sort("year")
)
national_check
{
    "province_rows": province_check.height,
    "provinces": province_check["province"].n_unique(),
    "district_rows": province_check["districts"].sum(),
    "without_reference": province_check["reference"].null_count(),
    "without_sum": province_check["district_sum"].null_count(),
    "differences": (province_check["difference"] != 0).sum(),
}
1
2
3
4
5
6
7
8
9
10
11
12
13
shape: (5, 6)
┌──────┬──────────────┬───────────┬──────┬───────────┬────────────┐
│ year ┆ district_sum ┆ districts ┆ line ┆ reference ┆ difference │
│ ---  ┆ ---          ┆ ---       ┆ ---  ┆ ---       ┆ ---        │
│ i32  ┆ i64          ┆ u32       ┆ u32  ┆ i64       ┆ i64        │
╞══════╪══════════════╪═══════════╪══════╪═══════════╪════════════╡
│ 2019 ┆ 51052236     ┆ 229       ┆ 4    ┆ 51052236  ┆ 0          │
│ 2020 ┆ 51082752     ┆ 229       ┆ 4    ┆ 51082752  ┆ 0          │
│ 2021 ┆ 51157486     ┆ 229       ┆ 4    ┆ 51157486  ┆ 0          │
│ 2022 ┆ 51229421     ┆ 229       ┆ 4    ┆ 51229421  ┆ 0          │
│ 2023 ┆ 51299993     ┆ 229       ┆ 4    ┆ 51299993  ┆ 0          │
└──────┴──────────────┴───────────┴──────┴───────────┴────────────┘
{'province_rows': 85, 'provinces': 17, 'district_rows': 1145, 'without_reference': 0, 'without_sum': 0, 'differences': 0}

Every regional and national sum matches, including the 2023 national total of 51,299,993. Swapping the counts for Busan’s Jung-gu and Seo-gu would leave both the Busan subtotal and the national total unchanged. To check either district’s count, we can return to its line in the report and read the column for that year.

Change from 2019 to 2023

The report uses its 2024 district names for all five years, so the endpoint counts refer to the same named districts. For each district, signed change is its 2023 population minus its 2019 population, in persons. Percentage change divides that difference by the district’s own 2019 population and multiplies by 100.

Signed change requires both endpoints; percentage change also requires a nonzero starting count. Before interpreting the report’s changes, the four constructed cases show how these requirements affect the results, including a district that gains residents after starting at zero.

In R, filter() selects 2019 and 2023, and pivot_wider() places pop_2019 and pop_2023 on one row per district. add_changes() subtracts the endpoints and uses if_else() to set the percentage to missing when the starting count is zero or missing. Arithmetic also gives a missing change if either endpoint is missing. The same function handles the zero and missing starting populations in endpoint_cases and the two observed counts for Haeundae-gu.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
endpoints <- coded_years |>
  filter(year %in% c(2019, 2023)) |>
  select(`District code`, line, province, district_key, year, population) |>
  pivot_wider(names_from = year, values_from = population, names_prefix = "pop_")
c(
  rows = nrow(endpoints),
  codes = n_distinct(endpoints$`District code`),
  missing_endpoints = sum(is.na(endpoints$pop_2019) | is.na(endpoints$pop_2023)),
  zero_bases = sum(endpoints$pop_2019 == 0, na.rm = TRUE)
)
add_changes <- function(pairs) {
  mutate(
    pairs,
    change = pop_2023 - pop_2019,
    percent = if_else(pop_2019 != 0, 100 * change / pop_2019, NA)
  )
}
endpoint_cases <- tibble(
  district = c("d1", "d2", "d3", "d4"),
  pop_2019 = c(100, 0, NA, 200),
  pop_2023 = c(130, 5, 40, 170)
)
add_changes(endpoint_cases)
changes <- add_changes(endpoints)
changes |>
  filter(`District code` == "02009") |>
  select(`District code`, district_key, pop_2019, pop_2023, change, percent)
1
2
3
4
5
6
7
8
9
10
11
12
13
             rows             codes missing_endpoints        zero_bases 
              229               229                 0                 0 
# A tibble: 4 × 5
  district pop_2019 pop_2023 change percent
  <chr>       <dbl>    <dbl>  <dbl>   <dbl>
1 d1            100      130     30      30
2 d2              0        5      5      NA
3 d3             NA       40     NA      NA
4 d4            200      170    -30     -15
# A tibble: 1 × 6
  `District code` district_key pop_2019 pop_2023 change percent
  <chr>           <chr>           <dbl>    <dbl>  <dbl>   <dbl>
1 02009           Haeundae-gu    370258   358841 -11417   -3.08

In Polars, first_year and last_year name the endpoint counts. A full join by District code includes districts from either year, with a null for a missing endpoint. validate="1:1" allows each code at most once per input. add_changes() computes change before a second with_columns() uses it for percent. A missing endpoint gives a null change. With no otherwise(), pl.when() also gives a null percentage when the starting population is zero.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
first_year = coded_years.filter(pl.col("year") == 2019).select(
    "District code", "line", "province", "district_key", pop_2019="population"
)
last_year = coded_years.filter(pl.col("year") == 2023).select(
    "District code", pop_2023="population"
)
endpoints = first_year.join(
    last_year, on="District code", how="full", coalesce=True, validate="1:1"
)
{
    "rows": endpoints.height,
    "codes": endpoints["District code"].n_unique(),
    "missing_endpoints": endpoints.filter(
        pl.col("pop_2019").is_null() | pl.col("pop_2023").is_null()
    ).height,
    "zero_bases": (endpoints["pop_2019"] == 0).sum(),
}


def add_changes(pairs):
    return pairs.with_columns(
        change=pl.col("pop_2023") - pl.col("pop_2019")
    ).with_columns(
        percent=pl.when(pl.col("pop_2019") != 0).then(
            100 * pl.col("change") / pl.col("pop_2019")
        )
    )


endpoint_cases = pl.DataFrame(
    {
        "district": ["d1", "d2", "d3", "d4"],
        "pop_2019": [100, 0, None, 200],
        "pop_2023": [130, 5, 40, 170],
    }
)
add_changes(endpoint_cases)
changes = add_changes(endpoints)
changes.filter(pl.col("District code") == "02009").select(
    "District code", "district_key", "pop_2019", "pop_2023", "change", "percent"
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{'rows': 229, 'codes': 229, 'missing_endpoints': 0, 'zero_bases': 0}
shape: (4, 5)
┌──────────┬──────────┬──────────┬────────┬─────────┐
│ district ┆ pop_2019 ┆ pop_2023 ┆ change ┆ percent │
│ ---      ┆ ---      ┆ ---      ┆ ---    ┆ ---     │
│ str      ┆ i64      ┆ i64      ┆ i64    ┆ f64     │
╞══════════╪══════════╪══════════╪════════╪═════════╡
│ d1       ┆ 100      ┆ 130      ┆ 30     ┆ 30.0    │
│ d2       ┆ 0        ┆ 5        ┆ 5      ┆ null    │
│ d3       ┆ null     ┆ 40       ┆ null   ┆ null    │
│ d4       ┆ 200      ┆ 170      ┆ -30    ┆ -15.0   │
└──────────┴──────────┴──────────┴────────┴─────────┘
shape: (1, 6)
┌───────────────┬──────────────┬──────────┬──────────┬────────┬───────────┐
│ District code ┆ district_key ┆ pop_2019 ┆ pop_2023 ┆ change ┆ percent   │
│ ---           ┆ ---          ┆ ---      ┆ ---      ┆ ---    ┆ ---       │
│ str           ┆ str          ┆ i64      ┆ i64      ┆ i64    ┆ f64       │
╞═══════════════╪══════════════╪══════════╪══════════╪════════╪═══════════╡
│ 02009         ┆ Haeundae-gu  ┆ 370258   ┆ 358841   ┆ -11417 ┆ -3.083526 │
└───────────────┴──────────────┴──────────┴──────────┴────────┴───────────┘

In the constructed cases, district d2 gained five residents from a starting count of zero, so its percentage change is undefined. District d3 has no 2019 count, so even the change in persons is unknown.

The report itself has both endpoints and a nonzero starting population for every district, so both measures can be calculated for all 229 districts. Haeundae-gu, for example, fell from 370,258 to 358,841 residents, a loss of 11,417 or about 3.08 percent.

Percentage change and national share

A district’s percentage change and its share of the national population answer different questions because they use different numerators and denominators. For Chuncheon-si, percentage change compares its gain or loss with its own 2019 population. Its national share is 100 times its 2023 population divided by the national total for 2023. The reconciled national total provides the denominator for the second calculation.

1
2
3
4
5
national_2023 <- national_check$district_sum[national_check$year == 2023]
changes |>
  filter(`District code` == "10001") |>
  mutate(national_2023 = national_2023, share_2023 = 100 * pop_2023 / national_2023) |>
  select(district_key, pop_2019, percent, pop_2023, national_2023, share_2023)
1
2
3
4
# A tibble: 1 × 6
  district_key pop_2019 percent pop_2023 national_2023 share_2023
  <chr>           <dbl>   <dbl>    <dbl>         <dbl>      <dbl>
1 Chuncheon-si   282597   -2.52   275489      51299993      0.537
1
2
3
4
5
6
7
8
9
national_2023 = national_check.filter(pl.col("year") == 2023)["district_sum"].item()
changes.filter(pl.col("District code") == "10001").select(
    "district_key",
    "pop_2019",
    "percent",
    "pop_2023",
    national_2023=pl.lit(national_2023, dtype=pl.Int64),
    share_2023=100 * pl.col("pop_2023") / national_2023,
)
1
2
3
4
5
6
7
8
shape: (1, 6)
┌──────────────┬──────────┬───────────┬──────────┬───────────────┬────────────┐
│ district_key ┆ pop_2019 ┆ percent   ┆ pop_2023 ┆ national_2023 ┆ share_2023 │
│ ---          ┆ ---      ┆ ---       ┆ ---      ┆ ---           ┆ ---        │
│ str          ┆ i64      ┆ f64       ┆ i64      ┆ i64           ┆ f64        │
╞══════════════╪══════════╪═══════════╪══════════╪═══════════════╪════════════╡
│ Chuncheon-si ┆ 282597   ┆ -2.515243 ┆ 275489   ┆ 51299993      ┆ 0.537016   │
└──────────────┴──────────┴───────────┴──────────┴───────────────┴────────────┘

Chuncheon-si lost about 2.52 percent of its own 2019 population, while its 2023 population made up about 0.537 percent of the national total. The first percentage describes change over time; the second describes the district’s contribution to a total in one year.

The largest changes

The opening question asks for the largest changes in numbers of residents. We therefore rank gains and losses together by abs(change), using the sign of change to identify their direction. District code breaks ties in ascending order. Percentage change accompanies the ranking to show how large each gain or loss is relative to that district’s starting population.

filter() selects districts with a known change for both the ranking and the counts of increases and decreases. Then arrange(desc(abs(change)), `District code`) orders the R rows by magnitude and then by code. head(5) returns up to five districts.

1
2
3
4
5
6
7
8
9
10
11
observed <- filter(changes, !is.na(change))
largest <- observed |>
  arrange(desc(abs(change)), `District code`) |>
  head(5)
select(largest, `District code`, province, district_key, pop_2019, pop_2023, change,
       percent)
c(
  repeated_magnitudes = nrow(observed) - n_distinct(abs(observed$change)),
  increases = sum(observed$change > 0),
  decreases = sum(observed$change < 0)
)
1
2
3
4
5
6
7
8
9
10
# A tibble: 5 × 7
  `District code` province    district_key   pop_2019 pop_2023 change percent
  <chr>           <chr>       <chr>             <dbl>    <dbl>  <dbl>   <dbl>
1 09003           Gyeonggi-do Goyang-si        872732   978616 105884   12.1 
2 09027           Gyeonggi-do Dongducheon-si   896832   967717  70885    7.90
3 09018           Gyeonggi-do Hanam-si         534420   603857  69437   13.0 
4 09022           Gyeonggi-do Uiwang-si        838381   906008  67627    8.07
5 09015           Gyeonggi-do Gwangmyeong-si   777849   844773  66924    8.60
repeated_magnitudes           increases           decreases 
                  2                  86                 143 

In Polars, filter() selects districts with a known change for both the ranking and the counts of increases and decreases. sort() with descending=[True, False] orders districts by absolute change from largest to smallest, then by district code in ascending order. head(5) returns up to five districts.

1
2
3
4
5
6
7
8
9
10
11
12
13
observed = changes.filter(pl.col("change").is_not_null())
largest = observed.sort(
    pl.col("change").abs(), "District code", descending=[True, False]
).head(5)
largest.select(
    "District code", "line", "district_key", "pop_2019", "pop_2023", "change", "percent"
)
{
    "repeated_magnitudes": observed.height - observed["change"].abs().n_unique(),
    "increases": (observed["change"] > 0).sum(),
    "decreases": (observed["change"] < 0).sum(),
    "largest_provinces": largest["province"].unique().to_list(),
}
1
2
3
4
5
6
7
8
9
10
11
12
13
shape: (5, 7)
┌───────────────┬──────┬────────────────┬──────────┬──────────┬────────┬───────────┐
│ District code ┆ line ┆ district_key   ┆ pop_2019 ┆ pop_2023 ┆ change ┆ percent   │
│ ---           ┆ ---  ┆ ---            ┆ ---      ┆ ---      ┆ ---    ┆ ---       │
│ str           ┆ u32  ┆ str            ┆ i64      ┆ i64      ┆ i64    ┆ f64       │
╞═══════════════╪══════╪════════════════╪══════════╪══════════╪════════╪═══════════╡
│ 09003         ┆ 92   ┆ Goyang-si      ┆ 872732   ┆ 978616   ┆ 105884 ┆ 12.132476 │
│ 09027         ┆ 116  ┆ Dongducheon-si ┆ 896832   ┆ 967717   ┆ 70885  ┆ 7.903933  │
│ 09018         ┆ 107  ┆ Hanam-si       ┆ 534420   ┆ 603857   ┆ 69437  ┆ 12.992964 │
│ 09022         ┆ 111  ┆ Uiwang-si      ┆ 838381   ┆ 906008   ┆ 67627  ┆ 8.06638   │
│ 09015         ┆ 104  ┆ Gwangmyeong-si ┆ 777849   ┆ 844773   ┆ 66924  ┆ 8.603726  │
└───────────────┴──────┴────────────────┴──────────┴──────────┴────────┴───────────┘
{'repeated_magnitudes': 2, 'increases': 86, 'decreases': 143, 'largest_provinces': ['Gyeonggi-do']}

In this synthetic report, all five of the largest population changes were gains in Gyeonggi-do, although 143 of the 229 districts lost residents. Goyang-si, recorded on line 92, ranks first: its population rose from 872,732 to 978,616, a gain of 105,884 or 12.1 percent. Hanam-si gained 69,437 residents. With a starting population of 534,420, that smaller gain represented a larger percentage increase of 13.0 percent. The ranking answers the question in numbers of residents, while the percentages explain the scale of each change within its district.

This post is licensed under CC BY-NC 4.0 by the author.