---
title: "A Complete Clinical Workflow: Reviewing and Finalising a Linkage"
subtitle: "When a single threshold isn't quite enough, from inspection through to a finished dataset"
author: "Dr Nicolas Smoll, SCPHU, Sunshine Coast Hospital and Health Service"
date: "`r Sys.Date()`"
output:
  html_document:
    toc: true
    toc_depth: 3
    toc_float: true
    theme: flatly
  pdf_document:
    toc: true
    toc_depth: 3
vignette: >
  %\VignetteIndexEntry{A Complete Clinical Workflow: Reviewing and Finalising a Linkage}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
# The worked data (the clutch datasets) live in mudnester; if it is not
# installed the vignette stops cleanly after this point. Phonetic blocking
# needs the phonics package (Suggests); those chunks are skipped without it.
has_mudnester <- requireNamespace("mudnester", quietly = TRUE) &&
  utils::packageVersion("mudnester") >= "0.9.0"   # the clutch datasets arrived in 0.9.0
has_phonics   <- requireNamespace("phonics", quietly = TRUE)
knitr::opts_chunk$set(
  fig.retina = 1,   # 1x figures: keeps the built HTML small for CRAN
  collapse   = TRUE,
  comment    = "#>",
  message    = FALSE,
  warning    = FALSE,
  fig.width  = 8,
  fig.height = 4.5,
  eval       = has_mudnester
)
```

```{r needs-mudnester, echo = FALSE, eval = !has_mudnester, results = "asis"}
cat("This vignette uses the clutch datasets from the mudnester package. Install mudnester (>= 0.9.0) to run it.")
knitr::knit_exit()
```

```{r load}
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")
```

## (*)> Overview

`vignette("linked-cohort")` walks through the standard `starling` workflow:
audit, block, link, plot, done. Most linkages follow exactly that path -- a
clean bimodal score distribution, a threshold that sits in the valley, and an
above-threshold count that matches expectations.

This vignette is for the case where that isn't quite enough: a small linkage
where every individual decision has a consequence. The scenario is a measles
response. A traveller returning from Indonesia was notified with measles in
August 2025, and the public health unit traced
`r nrow(clutch_contacts)` close contacts from the places the case had been
while infectious. For each contact the team needs to know, quickly, what the
Australian Immunisation Register (AIR) says about their MMR doses *before*
exposure: that decides who is offered MMR (within 72 hours), who is offered
normal human immunoglobulin (within six days), and who is excluded from work
or school [5].

Contact details were taken over the phone, so names are spelled as heard,
Medicare numbers are mostly absent, and some dates of birth are only a year
of birth. The linkage has to be right for each person, not just on average.
The pieces used here are documented elsewhere:
`murmuration(inspect_matches = TRUE)` (see `?murmuration`), `perch()` (see
`vignette("threshold-selection")`), and
`murmuration(resume_from_pairs = ...)`. This vignette shows them used
together, in order, against a decision an analyst actually has to make.

```{r contacts}
clutch_contacts |>
  count(exposure_setting, name = "contacts") |>
  knitr::kable(caption = "Where the contacts were exposed")
```

***

## (*)> Recap: getting to a scored (but not yet finalised) set of pairs

Contacts are a linelist of people with an exposure date, so they are cleaned
as a `"cohort"`, with the exposure date as the cohort entry date.

> **(*)> One vaccine type at a time.** Normally the AIR extract is filtered to
> the vaccine being studied -- here `filter(grepl("^Measles", antigen))`, which
> catches MMR and MMRV -- before `clean_the_nest(lie_nest_flat = TRUE)` and
> `murmuration()`. Otherwise `vax_date_1`, `vax_date_2`, ... interleave every
> vaccine the person has had, and the dose counts and `vaccination_status` mean
> "any vaccine". This design is the exception: "on the register with no MMR"
> and "not on the register at all" are different findings for a contact, so the
> *identity* linkage needs every registered person -- every antigen, and
> `drop_the_na_vax = FALSE` to keep people registered with no vaccine recorded.
> The MMR doses are then counted from the measles-only extract (Step 12), never
> from the mixed `vax_type_*` columns.

```{r prep}
contacts_clean <- clean_the_nest(
  clutch_contacts,
  data_type         = "cohort",
  drop_eggs         = TRUE,
  id_var            = "contact_id",
  lettername1       = "given_name",
  lettername2       = "family_name",
  dob               = "date_of_birth",
  gender            = "sex",
  postcode          = "postcode",
  medicare          = "medicare_number",
  cohort_entry_date = "exposure_date",
  keep_vars         = c("truth_id", "exposure_setting", "pep_type")
)

air_clean <- clean_the_nest(
  clutch_air,                  # every antigen: a person frame for the identity link
  data_type       = "vaccination",
  lie_nest_flat   = TRUE,
  drop_the_na_vax = FALSE,     # keep registered people with no vaccine recorded
  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",
  vax_type        = "antigen",
  vax_date        = "date_of_service",
  keep_vars       = "truth_id"
)

# Step 1: audit (see vignette("pre-linkage-quality") for what each flag means)
audit <- preflight(contacts_clean, air_clean,
                   linkage_vars = c("lettername1", "lettername2", "dob", "medicare10"),
                   id_col1      = "id_var",
                   id_col2      = "id_var",
                   date_cols    = "dob",
                   medicare_col = "medicare10",
                   verbose      = FALSE)
knitr::kable(audit$completeness, caption = "Completeness of the linkage variables")

# Step 2: Medicare validation -- invalid numbers become NA
contacts_checked <- contacts_clean |>
  check_medicare(verbose = FALSE) |>
  mutate(medicare10 = if_else(medicare_valid %in% 0L, NA_character_, medicare10))
air_checked <- air_clean |>
  check_medicare(verbose = FALSE) |>
  mutate(medicare10 = if_else(medicare_valid %in% 0L, NA_character_, medicare10))

# Step 3: blocking on gender + birth year
contacts_blocked <- contacts_checked |>
  flock(block1_vars = c("gender", "birth_year"), birth_year_col = "dob")
air_blocked <- air_checked |>
  flock(block1_vars = c("gender", "birth_year"), birth_year_col = "dob")
```

Medicare is missing for
`r round(100 * mean(is.na(contacts_checked$medicare10)))`% of contacts, so it
is left out of the comparison: the key is first name, last name and date of
birth -- the same three fields as the exact key of a regional Queensland
COVID-19 vaccine effectiveness linkage study [1], compared here with tolerance
for spelling. Three variables put a much lower
ceiling on the weights than the five the default of 16 is calibrated for (see
`vignette("threshold-selection")`, where no three-variable pair reaches 16),
so the provisional threshold is 7.

`clean_the_nest()` returns both the first given name (`lettername1`) and all
given names squeezed together (`lettername1_full`). Is either the better
first-name field for these contacts?

```{r given-names}
# each contact next to the same person's AIR record (truth_id: measurement only)
contacts_clean |>
  inner_join(air_clean, by = "truth_id", suffix = c("_contact", "_air")) |>
  summarise(
    first_given_name_agrees_pct = round(100 * mean(lettername1_contact == lettername1_air,
                                                   na.rm = TRUE), 1),
    all_given_names_agree_pct   = round(100 * mean(lettername1_full_contact == lettername1_full_air,
                                                   na.rm = TRUE), 1)
  ) |>
  knitr::kable()
```

A name given over the phone is almost always a single given name, so the two
fields agree with the AIR about equally often here, and `lettername1` is used.

***

## (*)> Step 4: Stop before deciding

Instead of letting `murmuration()` apply `threshold_value` and produce a
finished dataset in one step, `inspect_matches = TRUE` stops right after
blocking and EM scoring (Fellegi-Sunter weights [3], fitted with `reclin2`
[4]). `inspect_extra_vars` joins extra context -- postcode,
Medicare where known -- into the review table alongside the compared fields.

```{r inspect}
review <- murmuration(
  data_x             = contacts_blocked,  # one row per contact
  data_y             = air_blocked,       # one row per registered AIR person
  linkage_type       = "cohort2event",
  event_type         = "vaccination",
  id_var             = "id_var",
  blocking_var       = "block1",          # gender + birth year
  compare_vars       = c("lettername1", "lettername2", "dob"),  # Medicare mostly absent
  threshold_value    = 7,                 # provisional: only marks the pairs
  inspect_matches    = TRUE,              # stop after scoring
  inspect_extra_vars = c("postcode", "medicare10", "truth_id")  # context, not scored
)

n_accepted_pairs    <- sum(review$threshold)
n_accepted_contacts <- n_distinct(review$id_var.x[review$threshold])
```

`review` is the full candidate-pairs table --
`r format(nrow(review), big.mark = ",")` pairs, not only the
`r n_accepted_pairs` that cleared 7 -- with the field values from both
sides (`lettername1.x`/`.y`, `dob.x`/`.y`, `id_var.x`/`.y`, ...), a mechanical
`threshold` column (`weights >= 7`), and an empty `match_override` column
waiting to be filled in. The `truth_id` columns are there only so this
teaching example can be graded; real contact data has no such column.

***

## (*)> Step 5: See the shape of the problem

```{r plot-review, fig.cap = "Contact-to-AIR candidate-pair weights, run directly on the inspect_matches output."}
murmuration_plot(review, max_levels = 10)
```

`murmuration_plot()` picks up `threshold_value` and `blocking_var` straight
off `review`'s attributes. The distribution is bimodal, with the match
cluster at about 10 -- the ceiling when all three fields agree.

***

## (*)> Step 6: Quantify the trade-off across candidate cutoffs

```{r perch-review}
sweep <- perch(review,
               n_records_primary = nrow(contacts_blocked),
               thresholds        = seq(4, 11, by = 0.5),
               report            = FALSE,
               plot              = FALSE)

sweep |>
  select(threshold, n_above, n_clerical, link_rate) |>
  knitr::kable(caption = "Accepted pairs and clerical burden by threshold")
```

`review` already *is* the pairs-level table, so it goes straight into
`perch()`. The steep fall in accepted pairs ends at about 7; above that the
count drifts down slowly as true matches with one imperfect field start to
drop out. So 7 sits at the edge of the valley, and the threshold choice
itself isn't the issue -- the next step is.

***

## (*)> Step 7: When the numbers don't add up

The threshold accepted `r n_accepted_pairs` pairs for
`r n_accepted_contacts` contacts, so some
contacts have more than one plausible AIR record. A well-chosen threshold in a
clean valley guarantees the *bulk* of the separation is right; it says
nothing about which of two candidates is the person. Left alone,
`murmuration()` keeps the highest-scoring accepted candidate, and the highest
score is not always the right person.

```{r suspects}
# accepted candidates per contact
accepted_counts <- review |>
  as.data.frame() |>
  filter(threshold) |>
  count(id_var.x, name = "n_accepted")

multi_ids  <- accepted_counts |> filter(n_accepted > 1) |> pull(id_var.x)
linked_ids <- accepted_counts |> pull(id_var.x)

review <- review |>
  mutate(competing = threshold & id_var.x %in% multi_ids)   # one of several accepted

review |>
  as.data.frame() |>
  filter(competing) |>
  select(id_var.x, lettername1.x, lettername1.y, lettername2.x, lettername2.y,
         dob.x, dob.y, postcode.x, postcode.y, weights) |>
  arrange(id_var.x, desc(weights)) |>
  knitr::kable(digits = 1, caption = "Contacts with more than one accepted AIR candidate")

n_jan1 <- contacts_blocked |>
  filter(format(dob, "%m-%d") == "01-01") |>
  nrow()
```

Reading down that list with the names and dates of birth in front of you is
the point. Two kinds of row recur: a common name with a shared birth year and
a different day and month, and a date of birth of 1 January -- a placeholder
entered when a contact gave only their year of birth over the phone
(`r n_jan1` contacts), which
makes day/month disagreement meaningless -- with a placeholder, the
highest-scoring candidate is not always the right one. The score alone cannot
tell those apart. The postcode, joined in as context rather than scored,
settles many of them; a phone call settles the rest.

It is also worth checking the *other* direction -- contacts with no accepted
candidate whose best pair falls just short:

```{r near-miss}
review <- review |>
  mutate(near_miss = weights >= 6 & !threshold & !(id_var.x %in% linked_ids))

review |>
  as.data.frame() |>
  filter(near_miss) |>
  select(id_var.x, lettername1.x, lettername1.y, lettername2.x, lettername2.y,
         dob.x, dob.y, weights) |>
  knitr::kable(digits = 1, caption = "Near misses: weight 6-7, contact otherwise unlinked")
```

Here the typical story is a name typed as heard (a dropped or swapped letter)
with an exact date of birth -- one noisy field holding back a true match.

***

## (*)> Step 8: Record the judgement

`match_override` takes `"match"`, `"non-match"`, or `NA` (defer to the
mechanical threshold). In a real response, the decision for each listed pair
comes from the follow-up call or the GP record. In this teaching dataset
`truth_id` stands in for that call:

```{r override}
review <- review |>
  mutate(in_review = competing | near_miss)
review_untouched <- review    # kept unchanged for comparison in Step 10

review <- review |>
  mutate(match_override = if_else(
    in_review,
    if_else(truth_id.x == truth_id.y, "match", "non-match"),  # the follow-up call
    match_override
  ))

review |>
  as.data.frame() |>
  count(match_override, name = "pairs") |>
  knitr::kable()
```

### A note on documentation

`match_override` only records *what* was decided, not *why*. For anything
that might need to be defended in an outbreak report or a data governance
review, add a free-text column of your own alongside it -- `murmuration()`
ignores columns it doesn't recognise:

```{r reason-column}
review <- review |>
  mutate(override_reason = case_when(
    in_review & threshold  ~ "Several accepted AIR candidates: identity confirmed at follow-up call",
    in_review & !threshold ~ "Near miss (weight 6-7): identity confirmed at follow-up call",
    TRUE                   ~ NA_character_
  ))

review |>
  as.data.frame() |>
  filter(!is.na(override_reason)) |>
  count(override_reason, match_override, name = "pairs") |>
  knitr::kable()
```

***

## (*)> Step 9: Finish the linkage

`resume_from_pairs` applies the recorded overrides, falls back to
`weights >= threshold_value` for everything else, and then runs exactly the
same event-window logic a normal `murmuration()` call uses. The window keeps
doses given on or before the exposure date (`days_before = 0`, no look-back
limit) -- MMR given as post-exposure prophylaxis is a separate question.
`contacts_blocked`/`air_blocked` must be the same data frames used to build
`review`, since its `.x`/`.y` columns are row indices into them.

```{r finish}
linked_reviewed <- murmuration(
  data_x            = contacts_blocked,     # the SAME frames that built review
  data_y            = air_blocked,
  linkage_type      = "cohort2event",
  event_type        = "vaccination",
  event_date        = "cohort_entry_date",  # the exposure date
  id_var            = "id_var",
  threshold_value   = 7,                    # used wherever match_override is NA
  vax_window        = list(days_before = 0, days_after = 0, lookback_days = Inf),
  resume_from_pairs = review                # the reviewed table
)
```

The console output from this call reports how many manual overrides were
applied (`r sum(!is.na(review$match_override))` here) alongside the usual
linkage diagnostics -- worth checking that the count matches what you expect
before moving on.

***

## (*)> Step 10: Confirm the review actually helped

Resuming from the untouched copy reproduces the plain threshold-7 linkage
without re-fitting anything, so the two can be compared directly against the
truth:

```{r validate}
linked_naive <- murmuration(
  data_x            = contacts_blocked,
  data_y            = air_blocked,
  linkage_type      = "cohort2event",
  event_type        = "vaccination",
  event_date        = "cohort_entry_date",
  id_var            = "id_var",
  threshold_value   = 7,
  vax_window        = list(days_before = 0, days_after = 0, lookback_days = Inf),
  resume_from_pairs = review_untouched      # no overrides: the plain threshold-7 linkage
)

n_true <- contacts_blocked |>
  filter(truth_id %in% air_blocked$truth_id) |>
  nrow()

# the truth_id behind each matched AIR record -- used only to grade the links
air_truth <- air_blocked |>
  select(id_var_y = id_var, truth_id_air = truth_id)

review_summary <- bind_rows(
  linked_naive    |> mutate(linkage = "Threshold 7 only"),
  linked_reviewed |> mutate(linkage = "Threshold 7 + review")
) |>
  left_join(air_truth, by = "id_var_y") |>
  group_by(linkage) |>
  summarise(links   = sum(!is.na(truth_id_air)),
            correct = sum(truth_id_air == truth_id, na.rm = TRUE)) |>
  mutate(precision_pct = round(100 * correct / links, 1),
         recall_pct    = round(100 * correct / n_true, 1))

knitr::kable(review_summary, caption = paste("Contacts with a true AIR record:", n_true))

n_pairs_reviewed    <- sum(review$in_review)
n_contacts_reviewed <- n_distinct(review$id_var.x[review$in_review])
```

The review touched `r n_pairs_reviewed` pairs for
`r n_contacts_reviewed` contacts -- an afternoon's
phone calls, not a re-linkage -- and fixed errors in *both* directions. No
amount of re-tuning `threshold_value` could do that, because the errors sit
on opposite sides of the line.

***

## (*)> Step 11: A second pass for the contacts still unlinked

Blocking on birth year can never find a contact whose date of birth is
missing or wrong by a year. A second pass blocked on the Soundex code of the
surname (plus gender) catches a different set of errors -- see
`vignette("pre-linkage-quality")`. It is scored on all contacts, so the EM
model sees the full picture, and its links are used only for contacts the
first pass left unlinked.

```{r pass2, eval = has_mudnester && has_phonics}
contacts_phon <- contacts_checked |>
  flock(block1_vars     = c("lettername2_soundex", "gender"),
        phonetic_vars   = c("lettername1", "lettername2"),
        phonetic_method = "soundex")
air_phon <- air_checked |>
  flock(block1_vars     = c("lettername2_soundex", "gender"),
        phonetic_vars   = c("lettername1", "lettername2"),
        phonetic_method = "soundex")

linked_pass2 <- murmuration(
  data_x          = contacts_phon,
  data_y          = air_phon,
  linkage_type    = "cohort2event",
  event_type      = "vaccination",
  event_date      = "cohort_entry_date",
  id_var          = "id_var",
  blocking_var    = "block1",            # Soundex(surname) + gender
  compare_vars    = c("lettername1", "lettername2", "dob"),
  threshold_value = 6,                   # chosen from this pass's own sweep (below)
  vax_window      = list(days_before = 0, days_after = 0, lookback_days = Inf),
  keep_pairs_pred = TRUE
)

sweep_sdx <- perch(attr(linked_pass2, "pairs_pred"),
                   n_records_primary = nrow(contacts_phon),
                   thresholds        = seq(4, 11, by = 1),
                   report            = FALSE,
                   plot              = FALSE)

sweep_sdx |>
  select(threshold, n_above, n_clerical) |>
  knitr::kable(caption = "Second pass (Soundex block): accepted pairs by threshold")
```

Weights from different blocking passes are not on the same scale. Inside a
Soundex block every candidate already shares a surname code, so surname
agreement carries almost no weight, while date-of-birth agreement -- no longer
helped by a shared birth-year block -- carries much more; the threshold for
this pass is chosen from its own sweep (6 here), not carried over from pass
one.

```{r pass2-gain, eval = has_mudnester && has_phonics}
first_pass_ids <- linked_reviewed |>
  filter(!is.na(id_var_y)) |>
  pull(id_var)

pass2_new <- linked_pass2 |>
  filter(!(id_var %in% first_pass_ids), !is.na(id_var_y)) |>
  select(id_var, id_var_y, truth_id) |>
  left_join(air_truth, by = "id_var_y") |>
  mutate(correct = truth_id_air == truth_id)

tibble(
  measure = c("Contacts unlinked after pass one", "Linked by pass two",
              "of which correct"),
  value   = c(nrow(contacts_blocked) - length(first_pass_ids),
              nrow(pass2_new), sum(pass2_new$correct))
) |>
  knitr::kable()
```

### The deterministic alternative

The same phonetic codes give a threshold-free option:
`method = "deterministic"` with the Soundex codes in place of the names. It
tolerates spelling variants (`Smith`/`Smyth`) that the published exact key [1]
cannot, but has no tolerance at all for a wrong date of birth.

```{r deterministic, eval = has_mudnester && has_phonics}
det_exact <- murmuration(
  data_x       = contacts_phon,
  data_y       = air_phon,
  linkage_type = "cohort2event",
  event_type   = "vaccination",
  method       = "deterministic",    # every compare_vars field must match exactly
  event_date   = "cohort_entry_date",
  id_var       = "id_var",
  blocking_var = "block1",           # required, though exact matching ignores it
  compare_vars = c("lettername1", "lettername2", "dob"),
  vax_window   = list(days_before = 0, days_after = 0, lookback_days = Inf)
)
det_phonetic <- murmuration(
  data_x       = contacts_phon,
  data_y       = air_phon,
  linkage_type = "cohort2event",
  event_type   = "vaccination",
  method       = "deterministic",
  event_date   = "cohort_entry_date",
  id_var       = "id_var",
  blocking_var = "block1",
  compare_vars = c("lettername1_soundex", "lettername2_soundex", "dob"),  # the codes match exactly
  vax_window   = list(days_before = 0, days_after = 0, lookback_days = Inf)
)

bind_rows(
  det_exact       |> mutate(key = "Exact: first name + last name + DOB [1]"),
  det_phonetic    |> mutate(key = "Soundex(first name) + Soundex(last name) + DOB"),
  linked_reviewed |> mutate(key = "Probabilistic, reviewed (Steps 4-10)")
) |>
  left_join(air_truth, by = "id_var_y") |>
  group_by(key) |>
  summarise(links   = sum(!is.na(truth_id_air)),
            correct = sum(truth_id_air == truth_id, na.rm = TRUE)) |>
  knitr::kable(caption = paste("Contacts with a true AIR record:", n_true))
```

***

## (*)> Step 12: From linkage to action

The finished linkage gives each contact's AIR person (`id_var_y`). The MMR
doses come from the measles-only extract -- one vaccine type -- joined on that
identifier and counted if given on or before the exposure date (one dose per
day, since the AIR repeats some encounters). `murmuration()` also returns
`vaccination_status`, but here that says whether *any* vaccine falls inside the
window, because the person frame holds every antigen, so for a measles contact
it answers the wrong question:

```{r mmr-status}
final <- linked_reviewed
if (has_phonics) {
  final <- bind_rows(
    linked_reviewed |> filter(!is.na(id_var_y)),               # linked in pass one
    linked_pass2    |> filter(!(id_var %in% first_pass_ids))   # the rest, from pass two
  )
}

# ONE vaccine type: MMR and MMRV doses only
mmr_doses <- clutch_air |>
  filter(grepl("^Measles", antigen)) |>
  distinct(id_var_y = air_id, date_of_service)

mmr_before_exposure <- final |>
  select(id_var, id_var_y, cohort_entry_date) |>
  inner_join(mmr_doses, by = "id_var_y", relationship = "many-to-many") |>
  filter(date_of_service <= cohort_entry_date) |>
  count(id_var, name = "mmr_doses")

final <- final |>
  left_join(mmr_before_exposure, by = "id_var") |>
  mutate(mmr_doses  = coalesce(mmr_doses, 0L),
         air_status = case_when(is.na(id_var_y) ~ "Not found on the AIR",
                                mmr_doses == 0  ~ "On the AIR, no MMR before exposure",
                                mmr_doses == 1  ~ "1 MMR dose",
                                TRUE            ~ "2+ MMR doses"))

final |>
  count(air_status, pep_type, name = "contacts") |>
  knitr::kable(caption = "AIR status at exposure by post-exposure management recorded")
final |>
  count(air_status, vaccination_status, name = "contacts") |>
  knitr::kable(caption = "MMR status against murmuration()'s any-vaccine vaccination_status")
```

The same table from the truth shows how much the linkage itself changed the
picture:

```{r mmr-truth}
mmr_truth <- clutch_contacts |>
  select(id_var = contact_id, truth_id, exposure_date) |>
  inner_join(clutch_air |>
               filter(grepl("^Measles", antigen)) |>
               distinct(truth_id, date_of_service),
             by = "truth_id", relationship = "many-to-many") |>
  filter(date_of_service <= exposure_date) |>
  count(id_var, name = "mmr_truth")

final |>
  left_join(mmr_truth, by = "id_var") |>
  mutate(mmr_truth        = coalesce(mmr_truth, 0L),
         air_status_truth = case_when(!(truth_id %in% clutch_air$truth_id) ~ "Not found on the AIR",
                                      mmr_truth == 0 ~ "On the AIR, no MMR before exposure",
                                      mmr_truth == 1 ~ "1 MMR dose",
                                      TRUE           ~ "2+ MMR doses")) |>
  count(linked = air_status, truth = air_status_truth, name = "contacts") |>
  knitr::kable(caption = "AIR status from the linkage against the truth")
```

"On the AIR, no MMR before exposure" is the group that drives the response,
but it is not the same as "susceptible". Contacts born before 1966 are
presumed immune [5]; adults born after 1966 may have been vaccinated before the
AIR recorded adult doses. The linkage tells the team *who to ask*, which is
the decision it exists to support. Contacts who could not be found -- the
`r sum(is.na(contacts_blocked$dob))` with no date of birth at all are among
them -- go to a manual search, not to an automatic "unvaccinated".

***

## (*)> When this workflow is (and isn't) worth it

Most linkages should not need this. It costs analyst time, and applying it
routinely to every linkage would defeat the purpose of having an automated
threshold in the first place. Reach for it when:

- an above-threshold (or below-threshold) count doesn't match an
  independent expectation, or several candidates compete for one person
- specific pairs are individually consequential enough to justify a human
  decision -- an outbreak response like this one, where every contact's
  status changes what is offered to them, rather than a large cohort where
  individual misclassifications wash out
- a data governance or ethics review requires documented, auditable
  decisions on ambiguous matches rather than an unexamined cutoff -- the
  record-by-record resolution an infant immunisation coverage study applied
  to its birth-register records with identifier errors [2]

It is not a substitute for good blocking and a well-chosen `compare_vars`
set -- if dozens or hundreds of pairs need individual review, that's a signal
the linkage design needs revisiting (see `vignette("pre-linkage-quality")`
and `vignette("threshold-selection")`), not a signal to review more pairs by
hand.

***

## (*)> Summary: the complete review-and-finalise workflow

```{r workflow-summary, eval = FALSE}
library(starling)
library(mudnester)
library(dplyr)

# 1-3: clean, audit, Medicare validation, blocking
contacts <- clutch_contacts |>
  clean_the_nest(data_type = "cohort", cohort_entry_date = "exposure_date", ...) |>
  check_medicare() |>
  flock(block1_vars = c("gender", "birth_year"), birth_year_col = "dob")

# every registered person for the identity link (the exception to one-vaccine-at-a-time)
air <- clutch_air |>
  clean_the_nest(data_type = "vaccination", lie_nest_flat = TRUE,
                 drop_the_na_vax = FALSE, ...) |>
  check_medicare() |>
  flock(block1_vars = c("gender", "birth_year"), birth_year_col = "dob")

# 4. Stop after scoring, before any threshold decision is applied
review <- murmuration(data_x = contacts, data_y = air,
  linkage_type = "cohort2event", event_type = "vaccination", id_var = "id_var",
  blocking_var = "block1", compare_vars = c("lettername1", "lettername2", "dob"),
  threshold_value = 7, inspect_matches = TRUE)

# 5-6. Look at the shape of the problem, and quantify it
murmuration_plot(review)
perch(review, n_records_primary = nrow(contacts))

# 7-8. Inspect competing candidates and near misses; record decisions with reasons
review <- review |>
  mutate(match_override  = case_when(... ~ "match", ... ~ "non-match", TRUE ~ match_override),
         override_reason = case_when(... ~ "..."))

# 9. Finish -- same event-window logic as a normal murmuration() call
linked <- murmuration(data_x = contacts, data_y = air,
  linkage_type = "cohort2event", event_type = "vaccination",
  event_date = "cohort_entry_date", id_var = "id_var", threshold_value = 7,
  vax_window = list(days_before = 0, days_after = 0, lookback_days = Inf),
  resume_from_pairs = review)

# 11. Optional second pass (Soundex block) for contacts still unlinked
# 12. Count MMR doses before exposure from the MEASLES-ONLY extract, joined on id_var_y
mmr <- clutch_air |>
  filter(grepl("^Measles", antigen)) |>
  distinct(id_var_y = air_id, date_of_service)
```

***

## (*)> 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. **Applied**: its exact key (full first name, last
   name and date of birth) is the deterministic comparator in Step 11 and the
   comparison set used throughout. **Precedent** for tolerant (probabilistic
   and phonetic) versions of the same key.
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**: the roughly
   10% of birth-register records with identifier or date-of-birth errors were
   resolved by weighted-score matching across several data points, record by
   record -- the decision this vignette makes explicit and auditable with
   `match_override`.
3. Fellegi IP, Sunter AB. A theory for record linkage. J Am Stat Assoc.
   1969;64(328):1183--1210.
4. van der Laan DJ. reclin2: a toolkit for record linkage and deduplication.
   R J. 2022;14(2):320--328.
5. Communicable Diseases Network Australia. Measles: CDNA national guidelines
   for public health units. Canberra: Australian Government Department of
   Health. Post-exposure prophylaxis windows and the presumption of immunity
   for people born before 1966.

***

## (*)> Session information

```{r session}
sessionInfo()
```
