library(starling)
library(mudnester)   # clean_the_nest() and the clutch_* datasets
library(dplyr)
library(ggplot2)

aviary_cols <- c(satin = "#325D88", chestnut = "#86251C", wattle = "#D8A31A",
                 evergreen = "#08403B", mud = "#A67D4C", slate = "#3E3F3A")

(*)> Why pre-linkage quality matters

The Fellegi-Sunter EM algorithm scores pairs by comparing field values. Poor data quality in any of those fields degrades the score distribution in ways that no threshold choice can fully recover:

  • High missingness in a comparison variable removes its contribution to the weight, so true matches drift down towards the non-match cluster.
  • Invalid Medicare numbers that happen to resemble another person’s add spurious weight to false pairs.
  • Name variation (nicknames, same-sound spellings, typos) is expected, but systematic encoding differences are not.
  • Inconsistent coding of a blocking field means true pairs are never even compared.

This vignette works through all four on two of the clutch teaching datasets shipped in mudnester: the notifiable-disease linelist (clutch_cases, 3,182 notifications) and the Australian Immunisation Register extract (clutch_air, 31,200 encounter rows). Both are synthetic – no real person data – but built with the error profiles of real NoCS and AIR extracts, following the notifications + AIR design of a regional Queensland vaccine effectiveness linkage study [1]. Each record carries a truth_id, which real data never has; we use it here only to measure how much each data-quality decision costs.


(*)> The raw extracts

clutch_cases |>
  select(notification_id, condition, first_name, surname, date_of_birth, sex,
         medicare_number) |>
  head(6) |>
  knitr::kable()
notification_id condition first_name surname date_of_birth sex medicare_number
NOC4304827 COVID-19 Edward Marshall 1956-10-08 M 6592585881
NOC6438426 COVID-19 Christine McDonald 1947-08-16 F 38484344462
NOC6729326 COVID-19 Carol Smith 1946-09-07 F 35400173562
NOC9260341 RSV Rohan Gupta 1944-03-07 M 5770215236
NOC9677547 RSV Margaret Taylor 1928-04-08 F 50345225221
NOC1271791 RSV HARPREET Sharma 1959-09-24 M NA

clutch_air |>
  select(air_id, given_name, family_name, date_of_birth, sex, medicare_card,
         medicare_irn, date_of_service, antigen) |>
  head(6) |>
  knitr::kable()
air_id given_name family_name date_of_birth sex medicare_card medicare_irn date_of_service antigen
AIR10010969 KATHLEEN WRIGHT 1933-02-19 F 4790506501 1 2023-08-03 COVID-19
AIR10010969 KATHLEEN WRIGHT 1933-02-19 F 4790506501 1 2023-08-03 Influenza
AIR10010969 KATHLEEN WRIGHT 1933-02-19 F 4790506501 1 2023-10-22 COVID-19
AIR10010969 KATHLEEN WRIGHT 1933-02-19 F 4790506501 1 2024-05-14 Influenza
AIR10010969 KATHLEEN WRIGHT 1933-02-19 F 4790506501 1 2024-06-14 COVID-19
AIR10010969 KATHLEEN WRIGHT 1933-02-19 F 4790506501 1 2024-12-20 COVID-19

Two things are already visible: the case linelist has mixed-case names and some 11-digit Medicare numbers (IRN appended), while the AIR stores upper-case family names, the 10-digit card number, and the IRN in a column of its own.


(*)> Cleaning both sides the same way

mudnester::clean_the_nest() standardises both extracts into the same schema (lettername1, lettername2, dob, gender, medicare10, …). About 10% of respiratory notifications have no onset date, so the specimen date stands in for them first – an event date that is NA would otherwise switch off the event window inside murmuration(). The AIR keeps the IRN in a column of its own, named with medicare_irn (a column called exactly medicare_irn is picked up automatically, with a message); on the notifications it comes from the 11th digit wherever one was recorded.

cases_raw <- clutch_cases |>
  mutate(
    onset_imputed = is.na(onset_date),                  # keep a flag
    onset_date    = coalesce(onset_date, specimen_date) # fall back to the specimen date
  )

cases_clean <- clean_the_nest(
  cases_raw,
  data_type   = "cases",
  drop_eggs   = TRUE,
  id_var      = "notification_id",
  diagnosis   = "condition",
  lettername1 = "first_name",
  lettername2 = "surname",
  dob         = "date_of_birth",
  gender      = "sex",
  postcode    = "postcode",
  medicare    = "medicare_number",
  onset_date  = "onset_date",
  keep_vars   = c("truth_id", "onset_imputed")
)

**(*)> One vaccine type at a time.** This vignette is about identifiers, so it pivots every AIR encounter into one row per person – a person frame whose vax_date_* columns mix COVID-19, influenza, zoster and MMR doses. That is fine for checking names, dates of birth and Medicare numbers. For a vaccine question, filter the AIR extract to that vaccine first (for example filter(antigen == "COVID-19")) before clean_the_nest(lie_nest_flat = TRUE) and murmuration(); otherwise the dose counts and vaccination_status mean “any vaccine”. vignette("linked-cohort") does exactly that.

air_clean <- clean_the_nest(
  clutch_air,                    # all antigens: a person frame for identifier checks
  data_type     = "vaccination",
  lie_nest_flat = TRUE,          # one row per person: vax_date_1, vax_type_1, ...
  drop_eggs     = TRUE,
  id_var        = "air_id",
  lettername1   = "given_name",
  lettername2   = "family_name",
  dob           = "date_of_birth",
  gender        = "sex",
  postcode      = "postcode",
  medicare      = "medicare_card",
  medicare_irn  = "medicare_irn",  # the IRN is stored apart from the card number
  vax_type      = "antigen",
  vax_date      = "date_of_service",
  keep_vars     = "truth_id"
)

c(cases = nrow(cases_clean), air_people = nrow(air_clean))
#>      cases air_people 
#>       3182      10326

lie_nest_flat = TRUE turned 31200 AIR rows into 10326 people. The 207 registration-only rows (people enrolled on the AIR with no vaccine recorded) were dropped by the default drop_the_na_vax = TRUE.

How names are standardised

Names are lowercased, transliterated to ASCII, and stripped of spaces and punctuation, so "O'Brien", "O Brien" and "OBRIEN" all agree: some source systems cannot store an apostrophe, a hyphen or a space at all, and the cleaned value has to be the same whichever system the name came through. Given names come back two ways: lettername1 is the first given name only (the first word, then stripped), and lettername1_full is every given name squeezed together. Examples from the AIR:

air_names <- clutch_air |>
  distinct(air_id, given_name, family_name) |>
  inner_join(air_clean |> select(air_id = id_var, lettername1, lettername1_full, lettername2),
             by = "air_id")

bind_rows(
  air_names |> filter(grepl(" ", trimws(given_name)))  |> head(3),  # compound given names
  air_names |> filter(grepl(" ", trimws(family_name))) |> head(2),  # spaced family names
  air_names |> filter(grepl("[-']", family_name))      |> head(3)   # hyphens, apostrophes
) |>
  select(-air_id) |>
  knitr::kable(caption = "Raw and cleaned AIR names")
Raw and cleaned AIR names
given_name family_name lettername1 lettername1_full lettername2
ZHI WEI LIU zhi zhiwei liu
LI NA WANG li lina wang
ZHI WEI CHEN zhi zhiwei chen
NATALIE VAN DER BERG natalie natalie vanderberg
WENDY VAN DER BERG wendy wendy vanderberg
CAITLIN O’BRIEN caitlin caitlin obrien
ROBERT O’NEILL robert robert oneill
NATALIE O’NEILL natalie natalie oneill

For the same person, how often does each cleaned field agree exactly between the notification and the AIR?

# each notification next to the same person's AIR record (truth_id: measurement only)
same_person <- cases_clean |>
  inner_join(air_clean, by = "truth_id", suffix = c("_case", "_air"))

name_agreement <- same_person |>
  summarise(
    l1      = mean(lettername1_case == lettername1_air, na.rm = TRUE),
    l1_full = mean(lettername1_full_case == lettername1_full_air, na.rm = TRUE),
    l2      = mean(lettername2_case == lettername2_air, na.rm = TRUE)
  )
name_agreement <- tibble(
  field     = c("lettername1 (first given name)",
                "lettername1_full (all given names)",
                "lettername2 (family name)"),
  agree_pct = round(100 * c(name_agreement$l1, name_agreement$l1_full,
                            name_agreement$l2), 1)
)
knitr::kable(name_agreement,
             caption = "Same person, notification vs AIR: % of cleaned names agreeing exactly")
Same person, notification vs AIR: % of cleaned names agreeing exactly
field agree_pct
lettername1 (first given name) 91.0
lettername1_full (all given names) 91.0
lettername2 (family name) 95.3

On notifications the two given-name fields agree about equally often (91% and 91%): where a given name is compound, both sources usually record all of it. The first-name rule earns its place where one source records middle names and the other does not – a flight manifest copies the passport, for instance (see vignette("clean-the-nest", package = "mudnester")). Compare on lettername1_full instead where compound given names are the norm, or use it for a second pass. Exact disagreement is not the end of a pair either: murmuration() scores names by string similarity, so a dropped letter still earns most of the weight.


(*)> preflight() – structured pre-linkage audit

preflight() runs a battery of checks across both datasets and returns a structured report. It is the recommended first step before any linkage call.

audit <- preflight(
  data1        = cases_clean,
  data2        = air_clean,
  linkage_vars = c("lettername1", "lettername2", "dob", "medicare10"),
  id_col1      = "id_var",
  id_col2      = "id_var",
  date_cols    = c("dob", "onset_date"),
  medicare_col = "medicare10",
  verbose      = FALSE
)

knitr::kable(audit$completeness, digits = 1,
             caption = "Completeness of the linkage variables")
Completeness of the linkage variables
variable dataset n_records n_present n_missing pct_missing
lettername1 data1 3182 3171 11 0.3%
lettername2 data1 3182 3182 0 0%
dob data1 3182 3179 3 0.1%
medicare10 data1 3182 2691 491 15.4%
lettername1 data2 10326 10326 0 0%
lettername2 data2 10326 10326 0 0%
dob data2 10326 10326 0 0%
medicare10 data2 10326 10221 105 1%
knitr::kable(audit$duplicates, digits = 1,
             caption = "Identifier uniqueness")
Identifier uniqueness
dataset n_records n_unique_ids n_duplicate_ids pct_duplicate
data1 3182 3182 0 0%
data2 10326 10326 0 0%
audit$flags
#> [1] "[FUTURE DATE] 'dob' in data1: 2 future date(s)"
#> [2] "[MEDICARE] 113 failed checksum in data1"

Medicare is missing for 15% of notifications – the single largest gap and, with reissued cards (below), the reason true matches split into separate clusters of linkage weight (see vignette("threshold-selection")). Gaps and errors on this scale are normal: a regional infant immunisation coverage study had to resolve identifier and date-of-birth errors in about one birth-register record in ten [2].


(*)> check_medicare() – Modulus 10 checksum validation

Australian Medicare numbers contain a check digit at position 9, calculated from positions 1–8 using the weights 1, 3, 7, 9, 1, 3, 7, 9. check_medicare() verifies this and returns a three-state flag:

Value Meaning
1L Checksum passes – number is internally consistent
0L Checksum fails – at least one digit is wrong
NA Missing, blank, or non-numeric – not verifiable
cases_checked <- cases_clean |>
  check_medicare(medicare_col = "medicare10", output_col = "medicare_valid",
                 verbose = FALSE)
air_checked <- air_clean |>
  check_medicare(medicare_col = "medicare10", output_col = "medicare_valid",
                 verbose = FALSE)

medicare_summary <- bind_rows(
  cases_checked |> transmute(dataset = "clutch_cases", medicare_valid),
  air_checked   |> transmute(dataset = "clutch_air",   medicare_valid)
) |>
  mutate(status = case_when(medicare_valid %in% 1L ~ "Valid",
                            medicare_valid %in% 0L ~ "Fails checksum",
                            TRUE                   ~ "Missing")) |>
  count(dataset, status) |>
  group_by(dataset) |>
  mutate(pct = round(100 * n / sum(n), 1)) |>
  ungroup()

knitr::kable(medicare_summary)
dataset status n pct
clutch_air Missing 105 1.0
clutch_air Valid 10221 99.0
clutch_cases Fails checksum 113 3.6
clutch_cases Missing 491 15.4
clutch_cases Valid 2578 81.0
ggplot(medicare_summary, aes(x = pct, y = dataset, fill = status)) +
  geom_col() +
  scale_fill_manual(values = c("Valid" = aviary_cols[["evergreen"]],
                               "Fails checksum" = aviary_cols[["chestnut"]],
                               "Missing" = "grey75")) +
  labs(x = "Percent of records", y = NULL, fill = NULL) +
  theme_minimal(base_size = 12) +
  theme(legend.position = "bottom")

clean_the_nest() already records a logical medicare_valid; check_medicare() replaces it with the three-state integer above, which keeps “missing” distinct from “wrong”.

What to do with invalid Medicare numbers

Do not discard the record – it may still link correctly on name and date of birth. Replace the invalid number with NA so it contributes nothing, rather than adding misleading partial agreement:

cases_checked <- cases_checked |>
  mutate(medicare10 = if_else(medicare_valid %in% 0L, NA_character_, medicare10))
air_checked <- air_checked |>
  mutate(medicare10 = if_else(medicare_valid %in% 0L, NA_character_, medicare10))

Households share a card; the IRN tells them apart

Households share a Medicare card: everyone on it has the same 10 digits and differs only by the IRN (individual reference number), the 11th digit. In the AIR extract:

air_checked |>
  filter(!is.na(medicare10)) |>
  count(medicare10, name = "people_on_card") |>   # people per card...
  count(people_on_card, name = "n_cards") |>       # ...and cards of each size
  knitr::kable(caption = "AIR people sharing a 10-digit Medicare number")
AIR people sharing a 10-digit Medicare number
people_on_card n_cards
1 2695
2 1994
3 533
4 319
5 123
6 8

A comparison that rewards Medicare agreement will therefore score parents, partners and children of the true person highly. That is why Medicare is a comparison variable alongside names and date of birth, never a blocking variable or a deterministic key on its own.

clean_the_nest() returns the IRN as medicare_irn and the person’s own number as medicare11 (medicare10 followed by the IRN): household members share medicare10 but never medicare11. The catch is how often each source records the IRN:

detail_levels <- c("Card number + IRN", "Card number only", "No valid number")

medicare_detail <- bind_rows(
  cases_checked |> transmute(dataset = "clutch_cases", medicare10, medicare_irn),
  air_checked   |> transmute(dataset = "clutch_air",   medicare10, medicare_irn)
) |>
  mutate(detail = case_when(!is.na(medicare10) & !is.na(medicare_irn) ~ detail_levels[1],
                            !is.na(medicare10)                        ~ detail_levels[2],
                            TRUE                                      ~ detail_levels[3]),
         detail = factor(detail, levels = rev(detail_levels))) |>
  count(dataset, detail, .drop = FALSE) |>
  group_by(dataset) |>
  mutate(pct = round(100 * n / sum(n), 1)) |>
  ungroup() |>
  arrange(desc(dataset), desc(detail))

pct_cases_with_irn <- medicare_detail |>
  filter(dataset == "clutch_cases", detail == "Card number + IRN") |>
  pull(pct)

knitr::kable(medicare_detail, caption = "How much of the Medicare number each source records")
How much of the Medicare number each source records
dataset detail n pct
clutch_cases Card number + IRN 662 20.8
clutch_cases Card number only 1916 60.2
clutch_cases No valid number 604 19.0
clutch_air Card number + IRN 10221 99.0
clutch_air Card number only 0 0.0
clutch_air No valid number 105 1.0
ggplot(medicare_detail, aes(x = pct, y = dataset, fill = detail)) +
  geom_col() +
  scale_fill_manual(values = c("Card number + IRN" = aviary_cols[["satin"]],
                               "Card number only"  = aviary_cols[["wattle"]],
                               "No valid number"   = "grey75"),
                    breaks = detail_levels) +
  labs(x = "Percent of records", y = NULL, fill = NULL) +
  theme_minimal(base_size = 12) +
  theme(legend.position = "bottom")
Medicare detail recorded, by source. Invalid numbers have already been set to NA.
Medicare detail recorded, by source. Invalid numbers have already been set to NA.

Where both sides do record it, the IRN separates the person from the rest of the household. Every notification with an IRN, paired with every AIR person on the same 10-digit card:

cases_with_irn <- cases_checked |>
  filter(!is.na(medicare10), !is.na(medicare_irn)) |>
  select(medicare10, medicare_irn, truth_id)
air_with_irn <- air_checked |>
  filter(!is.na(medicare10), !is.na(medicare_irn)) |>
  select(medicare10, medicare_irn, truth_id)

cases_with_irn |>
  inner_join(air_with_irn, by = "medicare10", suffix = c("_case", "_air"),
             relationship = "many-to-many") |>
  mutate(irn    = if_else(medicare_irn_case == medicare_irn_air, "IRN agrees", "IRN differs"),
         person = if_else(truth_id_case == truth_id_air, "Same person", "Different person")) |>
  count(irn, person, name = "pairs") |>
  knitr::kable(caption = "Notification-AIR pairs on the same card, IRN recorded on both")
Notification-AIR pairs on the same card, IRN recorded on both
irn person pairs
IRN agrees Same person 457
IRN differs Different person 721

The AIR records the IRN for almost everyone, but only 20.8% of notifications carry it – those where all 11 digits were entered. That makes the IRN a decisive review check rather than a routine comparison variable: a candidate pair that agrees on medicare10 but not on the IRN is a different person on the same card, and vignette("threshold-selection") uses it exactly that way. Scoring medicare11 alongside medicare10 would count the same card twice whenever both agree, which the Fellegi-Sunter model, assuming its fields are independent, cannot allow for.

medicare09 or medicare10?

clean_the_nest() splits the number into the account (medicare08), the account plus check digit (medicare09) and the full card number (medicare10). The tenth digit is the card issue: it changes every time a card is replaced. Comparing the same person’s number across the two sources shows what that costs:

medicare_agreement <- same_person |>
  filter(!is.na(medicare10_case), !is.na(medicare10_air)) |>
  summarise(m08 = mean(medicare08_case == medicare08_air),
            m09 = mean(medicare09_case == medicare09_air),
            m10 = mean(medicare10_case == medicare10_air))
medicare_agreement <- tibble(
  field = c("medicare08 (account)",
            "medicare09 (account + check digit)",
            "medicare10 (+ card issue digit)"),
  agree_pct = round(100 * c(medicare_agreement$m08, medicare_agreement$m09,
                            medicare_agreement$m10), 1)
)
knitr::kable(medicare_agreement,
             caption = "Same person, both sources recorded a number: % agreeing")
Same person, both sources recorded a number: % agreeing
field agree_pct
medicare08 (account) 95.7
medicare09 (account + check digit) 95.7
medicare10 (+ card issue digit) 78.0

Using medicare10 as a comparison variable therefore penalises everyone whose card was reissued between the two records – about 18 in every hundred pairs here. medicare09 keeps everything that identifies the account (household members still share it) without that penalty, and is the better comparison variable in new work. The other starling vignettes keep medicare10 so their weights line up with the package’s own examples; vignette("threshold-selection") measures what switching to medicare09 does to recall at the default threshold.


(*)> Inconsistent coding silently breaks blocking

clutch_hospital codes sex as "Male"/"Female"; every other source uses "M"/"F". A blocking key built from gender therefore never agrees across the two sources, and the true pairs are never compared:

clutch_hospital |> count(sex)
#>      sex    n
#> 1 Female 2281
#> 2   Male 1920
clutch_air      |> count(sex)
#>   sex     n
#> 1   F 15876
#> 2   M 15324

air_blocks <- clutch_air |>
  distinct(block = paste(sex, format(date_of_birth, "%Y")))

clutch_hospital |>
  distinct(block = paste(sex, format(birth_date, "%Y"))) |>
  semi_join(air_blocks, by = "block") |>
  nrow()   # zero: no hospital record would ever meet an AIR record
#> [1] 0

Harmonise first, then build blocks:

hosp_raw <- clutch_hospital |>
  mutate(sex = case_when(sex == "Male"   ~ "M",
                         sex == "Female" ~ "F"))

hosp_raw |>
  distinct(block = paste(sex, format(birth_date, "%Y"))) |>
  semi_join(air_blocks, by = "block") |>
  nrow()
#> [1] 205

(*)> flock() – blocking variable construction

flock() creates up to three blocking keys. murmuration() only compares pairs that share a key, so the choice trades computation against the chance that a true pair is split across blocks.

cases_blocked <- cases_checked |>
  flock(block1_vars    = "gender",
        block2_vars    = c("gender", "birth_year"),
        block3_vars    = "postcode",
        birth_year_col = "dob")
air_blocked <- air_checked |>
  flock(block1_vars    = "gender",
        block2_vars    = c("gender", "birth_year"),
        block3_vars    = "postcode",
        birth_year_col = "dob")

Because the clutch carries a ground-truth identifier, we can measure two things for each key before running any linkage: how many candidate pairs it generates, and what share of true pairs land in the same block (blocking recall). Written out key by key:

# candidate pairs = sum over shared keys of (records with the key) x (records with the key)
pairs_block1 <- cases_blocked |>
  filter(!is.na(block1)) |>
  count(block1, name = "n_x") |>
  inner_join(air_blocked |> count(block1, name = "n_y"), by = "block1") |>
  summarise(pairs = sum(as.numeric(n_x) * n_y)) |>
  pull(pairs)

pairs_block2 <- cases_blocked |>
  filter(!is.na(block2)) |>
  count(block2, name = "n_x") |>
  inner_join(air_blocked |> count(block2, name = "n_y"), by = "block2") |>
  summarise(pairs = sum(as.numeric(n_x) * n_y)) |>
  pull(pairs)

pairs_block3 <- cases_blocked |>
  filter(!is.na(block3)) |>
  count(block3, name = "n_x") |>
  inner_join(air_blocked |> count(block3, name = "n_y"), by = "block3") |>
  summarise(pairs = sum(as.numeric(n_x) * n_y)) |>
  pull(pairs)

# blocking recall: the share of true pairs that land in the same block
recall <- cases_blocked |>
  select(truth_id, x1 = block1, x2 = block2, x3 = block3) |>
  inner_join(air_blocked |> select(truth_id, y1 = block1, y2 = block2, y3 = block3),
             by = "truth_id") |>
  summarise(block1 = mean(x1 == y1, na.rm = TRUE),
            block2 = mean(x2 == y2, na.rm = TRUE),
            block3 = mean((x3 == y3) %in% TRUE))   # a missing postcode never matches

blocking_table <- tibble(
  block           = c("block1: gender", "block2: gender + birth year", "block3: postcode"),
  candidate_pairs = c(pairs_block1, pairs_block2, pairs_block3),
  blocking_recall = round(100 * c(recall$block1, recall$block2, recall$block3), 1)
)
knitr::kable(blocking_table, format.args = list(big.mark = ","))
block candidate_pairs blocking_recall
block1: gender 16,281,188 99.1
block2: gender + birth year 182,240 97.7
block3: postcode 2,228,368 92.6

Gender alone keeps nearly every true pair together but asks for 16.3 million comparisons. Gender + birth year is around 89 times cheaper and still keeps 97.7% of true pairs together. The pairs it loses have either a birth year that differs between sources (off by one, or a decade slip such as 1958 keyed as 1968) or a sex recorded differently (including "U", unknown, on the notification). Postcode loses everyone who moved house between the two records, and every notification with no postcode.

Phonetic blocking

A Soundex code of the surname is immune to birth-year errors and to many spelling variants (Smith/Smyth, McDonald/MacDonald, Reid/Reed), so it recovers a different set of true pairs:

# block1: Soundex(surname) + gender; block2: gender + birth year, for comparison
cases_phon <- cases_checked |>
  flock(block1_vars     = c("lettername2_soundex", "gender"),
        block2_vars     = c("gender", "birth_year"),
        phonetic_vars   = "lettername2",
        phonetic_method = "soundex",
        birth_year_col  = "dob")
air_phon <- air_checked |>
  flock(block1_vars     = c("lettername2_soundex", "gender"),
        block2_vars     = c("gender", "birth_year"),
        phonetic_vars   = "lettername2",
        phonetic_method = "soundex",
        birth_year_col  = "dob")

cases_phon |>
  distinct(lettername2, lettername2_soundex) |>
  head(8) |>
  knitr::kable()
lettername2 lettername2_soundex
marshall M624
mcdonald M235
smith S530
gupta G130
taylor T460
sharma S650
kding K352
rossi R200

pairs_soundex <- cases_phon |>
  filter(!is.na(block1)) |>
  count(block1, name = "n_x") |>
  inner_join(air_phon |> count(block1, name = "n_y"), by = "block1") |>
  summarise(pairs = sum(as.numeric(n_x) * n_y)) |>
  pull(pairs)

phonetic_recall <- cases_phon |>
  select(truth_id, sdx_x = block1, year_x = block2) |>
  inner_join(air_phon |> select(truth_id, sdx_y = block1, year_y = block2),
             by = "truth_id") |>
  mutate(same_soundex   = sdx_x == sdx_y,
         same_birthyear = year_x == year_y) |>
  summarise(year   = mean(same_birthyear, na.rm = TRUE),
            sdx    = mean(same_soundex, na.rm = TRUE),
            either = mean(same_birthyear | same_soundex, na.rm = TRUE))

tibble(
  strategy        = c("gender + birth year", "Soundex(surname) + gender",
                      "either (two passes, union)"),
  candidate_pairs = c(pairs_block2, pairs_soundex, pairs_block2 + pairs_soundex),
  blocking_recall = round(100 * c(phonetic_recall$year, phonetic_recall$sdx,
                                  phonetic_recall$either), 1)
) |>
  knitr::kable(format.args = list(big.mark = ","))
strategy candidate_pairs blocking_recall
gender + birth year 182,240 97.7
Soundex(surname) + gender 293,864 97.1
either (two passes, union) 476,104 99.0

Neither single key reaches the combined recall: each loses a different kind of error. This is the case for multi-pass blocking – run murmuration() once per key and keep the best-scoring link per record:

# For a vaccine question, the AIR side holds ONE vaccine type (see the callout above)
air_covid_phon <- clutch_air |>
  filter(antigen == "COVID-19") |>
  clean_the_nest(data_type = "vaccination", lie_nest_flat = TRUE, ...) |>
  check_medicare() |>
  flock(block1_vars     = c("lettername2_soundex", "gender"),
        block2_vars     = c("gender", "birth_year"),
        phonetic_vars   = "lettername2",
        phonetic_method = "soundex",
        birth_year_col  = "dob")

# pass 1: block on gender + birth year
linked_year <- murmuration(
  data_x          = cases_phon,
  data_y          = air_covid_phon,
  linkage_type    = "cohort2event",
  event_type      = "vaccination",
  event_date      = "onset_date",
  id_var          = "id_var",
  blocking_var    = "block2",             # gender + birth year
  compare_vars    = c("lettername1", "lettername2", "dob", "medicare10"),
  threshold_value = 8
)

# pass 2: block on Soundex(surname) + gender
linked_sdx <- murmuration(
  data_x          = cases_phon,
  data_y          = air_covid_phon,
  linkage_type    = "cohort2event",
  event_type      = "vaccination",
  event_date      = "onset_date",
  id_var          = "id_var",
  blocking_var    = "block1",             # Soundex(surname) + gender
  compare_vars    = c("lettername1", "lettername2", "dob", "medicare10"),
  threshold_value = 8
)

# keep the best-scoring link per case across both passes
linked_all <- bind_rows(linked_year, linked_sdx) |>
  arrange(desc(threshold), desc(weights)) |>
  distinct(id_var, .keep_all = TRUE)

Choosing blocking variables for Australian datasets

Dataset size Recommended block Rationale
< 10 000 records gender Broadest; halves candidate space immediately
10 000–500 000 gender + birth_year composite Balances sensitivity and specificity
> 500 000 postcode + birth_year Fine-grained; requires high postcode completeness
Names captured verbally (contact tracing) Soundex/Metaphone of surname + gender, as a second pass Tolerates spelling variation and date-of-birth errors

(*)> Putting it together

library(starling)
library(mudnester)
library(dplyr)

# 1. Clean both sources the same way (impute missing onset dates first)
cases <- clutch_cases |>
  mutate(onset_date = coalesce(onset_date, specimen_date)) |>
  clean_the_nest(data_type = "cases", id_var = "notification_id", ...)

# ... and the AIR for ONE vaccine type
air <- clutch_air |>
  filter(antigen == "COVID-19") |>
  clean_the_nest(data_type = "vaccination", lie_nest_flat = TRUE,
                 medicare = "medicare_card", medicare_irn = "medicare_irn", ...)

# 2. Audit
preflight(cases, air,
          linkage_vars = c("lettername1", "lettername2", "dob", "medicare10"),
          medicare_col = "medicare10")

# 3. Medicare: invalid numbers become NA; 4. Blocks (harmonise coding first)
cases <- cases |>
  check_medicare() |>
  mutate(medicare10 = if_else(medicare_valid %in% 0L, NA_character_, medicare10)) |>
  flock(block1_vars = c("gender", "birth_year"), birth_year_col = "dob")
air <- air |>
  check_medicare() |>
  mutate(medicare10 = if_else(medicare_valid %in% 0L, NA_character_, medicare10)) |>
  flock(block1_vars = c("gender", "birth_year"), birth_year_col = "dob")

# 5. Link -- see vignette("linked-cohort")

(*)> References

  1. Smoll NR, Al Imam MH, Shulz C, Booy R, Khandaker G. The effectiveness of vaccination for preventing hospitalisation with COVID-19 in regional Queensland: a data linkage study. Med J Aust. 2023;219(4):162–165. doi:10.5694/mja2.52019. Precedent: the linkage key (first name, last name, date of birth) and the notifications/admissions/AIR design these datasets mirror.
  2. Roughan WH, Cavanagh-Ochiai B, Barnekow D, Lottkowitz K, Schafer K, Camadoo L, Smoll NR. Infant respiratory syncytial virus (RSV) immunisation coverage in an Australian regional area, 1 May 2024 – 31 October 2025. Commun Dis Intell. 2026;50. doi:10.33321/cdi.2026.50.031. Precedent: about 10% of that study’s birth-register records carried identifier or date-of-birth errors, resolved with weighted-score matching; the clutch error rates are of the same order.

(*)> Session information

sessionInfo()
#> R version 4.5.2 (2025-10-31 ucrt)
#> Platform: x86_64-w64-mingw32/x64
#> Running under: Windows 11 x64 (build 26100)
#> 
#> Matrix products: default
#>   LAPACK version 3.12.1
#> 
#> locale:
#> [1] LC_COLLATE=C                       LC_CTYPE=English_Australia.utf8   
#> [3] LC_MONETARY=English_Australia.utf8 LC_NUMERIC=C                      
#> [5] LC_TIME=English_Australia.utf8    
#> 
#> time zone: Australia/Brisbane
#> tzcode source: internal
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#> [1] ggplot2_4.0.3   dplyr_1.2.1     mudnester_0.9.0 starling_2.0.0 
#> 
#> loaded via a namespace (and not attached):
#>  [1] sass_0.4.10         generics_0.1.4      tidyr_1.3.2        
#>  [4] lpSolve_5.6.23      stringi_1.8.7       digest_0.6.39      
#>  [7] magrittr_2.0.4      evaluate_1.0.5      grid_4.5.2         
#> [10] timechange_0.4.0    RColorBrewer_1.1-3  fastmap_1.2.0      
#> [13] jsonlite_2.0.0      purrr_1.2.1         scales_1.4.0       
#> [16] stringdist_0.9.17   jquerylib_0.1.4     cli_3.6.5          
#> [19] rlang_1.3.0         withr_3.0.2         cachem_1.1.0       
#> [22] yaml_2.3.12         otel_0.2.0          tools_4.5.2        
#> [25] parallel_4.5.2      vctrs_0.7.1         R6_2.6.1           
#> [28] lifecycle_1.0.5     lubridate_1.9.5     snakecase_0.11.1   
#> [31] stringr_1.6.0       janitor_2.2.1       pkgconfig_2.0.3    
#> [34] pillar_1.11.1       bslib_0.10.0        gtable_0.3.6       
#> [37] data.table_1.18.2.1 glue_1.8.0          Rcpp_1.1.1         
#> [40] xfun_0.56           tibble_3.3.1        tidyselect_1.2.1   
#> [43] rstudioapi_0.18.0   knitr_1.51          farver_2.1.2       
#> [46] htmltools_0.5.9     labeling_0.4.3      rmarkdown_2.31     
#> [49] phonics_1.3.10      compiler_4.5.2      S7_0.2.1           
#> [52] reclin2_0.6.0