Package {starling}


Title: Record Linkage for Public Health Surveillance
Version: 2.0.0
Description: Record linkage for public health surveillance datasets using either the Fellegi-Sunter probabilistic framework (via reclin2) or deterministic exact-key matching. Provides pre-linkage data quality auditing (preflight()), Medicare number checksum validation (check_medicare()), blocking variable construction (flock()), and the murmuration() linkage engine. murmuration() expresses linkage as a single cohort-to-event concept (linking a linelist of people to a dated stream of vaccination, hospitalisation, or case events within a before/during/after time window), with the historical four-code taxonomy (case-to-hospitalisation, vaccination-to-case, vaccination-to-hospitalisation, vaccination-to-event) retained as deprecated aliases. Also provides linkage weight distribution visualisation (murmuration_plot()) and threshold sensitivity analysis (perch()) with annotated AIHW, WA Data Linkage Unit, and PHRN reference benchmarks. perch() can be called standalone or triggered automatically mid-linkage via murmuration(perch_before_linking = TRUE). Includes synthetic datasets (cases_notifiable, vax_air) and three vignettes demonstrating the complete linkage workflow. Part of the aviary public health surveillance ecosystem.
License: MIT + file LICENSE
Encoding: UTF-8
Depends: R (≥ 4.1)
Imports: reclin2, dplyr (≥ 1.1.0), stringr, lubridate, rlang, ggplot2
Suggests: patchwork, plotly, phonics, mudnester (≥ 0.9.0), testthat (≥ 3.0.0), knitr, rmarkdown
VignetteBuilder: knitr
Config/roxygen2/version: 8.0.0
NeedsCompilation: no
Packaged: 2026-11-24 06:49:59 UTC; SmollN
Author: Nicolas Smoll ORCID iD [aut, cre]
Maintainer: Nicolas Smoll <nicolas.smoll@health.qld.gov.au>
Repository: CRAN
Date/Publication: 2026-11-24 07:10:03 UTC

starling: Probabilistic Record Linkage for Public Health Surveillance

Description

**Bird note**: Starlings form murmurations — thousands of individual birds moving as one coordinated, fluid shape with no central conductor, each responding only to its nearest neighbours until a single coherent pattern emerges from the flock. That is the visual the package is named for: murmuration() takes two separate, uncoordinated sets of records and lets pairwise local comparisons resolve into one coherent linked dataset. The supporting functions — flock(), preflight(), check_medicare(), and murmuration_plot() — are the pre-flight preparation and post-flight review that make the murmuration trustworthy.

Details

## Core workflow

  1. preflight() — Run a battery of pre-linkage data quality checks: completeness, duplicates, date plausibility, Medicare validity, name quality, and factor-level consistency across both datasets.

  2. check_medicare() — Validate Medicare numbers using the Services Australia Modulus 10 weighted checksum (can also be called standalone or from preflight()).

  3. flock() — Generate blocking variables (single-field, phonetic, or composite) to partition records before linkage.

  4. murmuration() — Link a cohort to a dated event stream (linkage_type = "cohort2event" with an event_type of "vaccination", "hospitalisation", or "case"), using either method = "probabilistic" (Fellegi-Sunter EM via reclin2) or method = "deterministic" (exact-key matching, no scoring). Of the historical four-code taxonomy, case-to-hospitalisation ("c2h") and vaccination-to-case ("v2c") still work but are deprecated in favour of cohort2event; vaccination-to-hospitalisation ("v2h") and vaccination-to-event ("v2e") are defunct as of 2.0.0 (use cohort2event with event_type = "vaccination", and a fixed event_date for an event linelist).

  5. murmuration_plot() — Plot the linkage weight distribution to confirm the threshold is placed at the natural valley between match and non-match clusters before finalising. Only applicable to method = "probabilistic" output — deterministic linkage has no score to plot.

## Threshold guidance

See murmuration_plot for a discussion of threshold selection. murmuration()'s default threshold_value is 16, calibrated for five comparison variables (first name, surname, date of birth, Medicare number, and postcode or gender) with an agreeing Medicare number. With fewer variables, or Medicare numbers that are missing or from an older card, true matches score lower: always plot the distribution first, and see vignette("threshold-selection", package = "starling").

Author(s)

Maintainer: Nicolas Smoll nicolas.smoll@health.qld.gov.au (ORCID)

Authors:


Validate Australian Medicare Numbers Using the Modulus 10 Checksum

Description

**Bird note**: Starlings are famously alert to impostors – a murmuration will immediately eject a bird that does not move quite right. check_medicare() plays the same sentinel role before linkage: it identifies impostors hiding in your Medicare number field before they corrupt the match scores. A single transposed digit in a Medicare number silently destroys a linkage pair; catching it here costs nothing compared to auditing a linked dataset afterwards.

Validates Australian Medicare numbers using the official Services Australia check-digit algorithm: a Modulus 10 weighted checksum on digits 1-8, verified against the 9th digit. The 10-digit Medicare card number has the structure XXXXXXXX C N: digits 1-8 identify the account, digit 9 (C) is the check digit derived from those 8 digits, and digit 10 (N) is the card's issue number, which changes every time a card is reissued – so one person can hold several 10-digit numbers over a lifetime. The Individual Reference Number (IRN), each person's position on a family card, is a separate 11th digit printed beside the name. Only the check digit (position 9) is validated here; neither the issue number nor the IRN is part of the checksum. For linkage, compare on medicare09 (account + check digit) from mudnester::clean_the_nest(), which survives card reissue.

Usage

check_medicare(
  data,
  medicare_col = "medicare10",
  output_col = "medicare_valid",
  verbose = TRUE,
  keep_digits = 10L
)

Arguments

data

A data frame containing a Medicare number column.

medicare_col

Character. Name of the column containing Medicare numbers. Values may include spaces or hyphens (stripped before validation). Default "medicare10" (the standardised name from mudnester::clean_the_nest()).

output_col

Character. Name of the new validation flag column added to data. Default "medicare_valid". Values: 1L for a valid checksum, 0L for an invalid checksum, NA for a missing or non-numeric entry.

verbose

Logical. If TRUE (default), prints a summary report to the console showing total records, valid count and percentage, invalid count, missing count, and a warning if the valid rate falls below 95%.

keep_digits

Integer. Either 9 or 10 (default). Length of a valid Medicare number string after stripping spaces and hyphens. Use 10 for the card number including its issue number (medicare10); use 9 for numbers stored without it (medicare09).

Details

## The Modulus 10 check-digit algorithm

The 9th digit of an Australian Medicare number is computed from the first 8 digits using positional weights 1, 3, 7, 9, 1, 3, 7, 9 (repeating 1-3-7-9). The check digit C is:

C = (d1*1 + d2*3 + d3*7 + d4*9 + d5*1 + d6*3 + d7*7 + d8*9) mod 10

If the computed value equals position 9 of the submitted number, the number passes validation.

## Interpreting the output flag

A flag of NA means the field was missing, blank, or non-numeric – these records cannot be linked on Medicare number but may still link via other variables. A flag of 0L means the number is present and numeric but the checksum fails – at least one digit is wrong and the number should not be used as a linkage variable. A flag of 1L means the checksum passes – the number is internally consistent, though it may still be wrong (e.g. a different person's valid card number).

A valid-checksum rate below 95% usually signals a systematic data entry or export issue and should be investigated before linkage.

Value

The input data frame with two new columns appended: medicare_clean (the Medicare number with spaces, hyphens, and dots stripped; NA for missing or empty entries) and the column named by output_col (integer flag: 1L valid, 0L invalid, NA missing or non-numeric).

References

Services Australia (2024). Medicare card number format and check digit.

See Also

preflight for a full pre-linkage audit. flock for blocking variable construction. murmuration for the linkage step. murmuration_plot for threshold visualisation.

Examples

## Not run: 
# Basic usage
cases_checked <- check_medicare(cases_clean)

# Custom column name
cases_checked <- check_medicare(cases_clean,
  medicare_col = "medicare_number",
  output_col   = "mcn_valid")

# Suppress console report
cases_checked <- check_medicare(cases_clean, verbose = FALSE)

# Exclude invalid Medicare numbers before linkage
cases_clean$medicare10 <- ifelse(
  cases_checked$medicare_valid == 1L,
  cases_clean$medicare10,
  NA_character_
)

# Validate 9-digit numbers (account + check digit, no issue number)
cases_checked <- check_medicare(cases_clean,
  medicare_col = "medicare09",
  keep_digits  = 9L)

## End(Not run)


Create Blocking Variables for Probabilistic Record Linkage

Description

**Bird note**: Before a murmuration forms, starlings first gather into loose flocks — smaller, manageable sub-groups that share a roost site or feeding ground. flock() plays that preparatory role: it partitions records into candidate sub-groups (blocks) so that murmuration() only compares records within the same block, rather than every record against every other. Good blocking dramatically reduces computation without sacrificing linkage quality, provided the blocking variable is near-complete and consistent across both datasets.

Generates one or more blocking variables from demographic fields already standardised by clean_the_nest(). Blocking variables partition the record space so that murmuration() only compares candidate pairs within the same block. Three strategies are offered:

All three strategies can be generated in a single flock() call and appended as new columns to the data frame, ready to pass to murmuration()'s blocking_var argument.

Usage

flock(
  data,
  block1_vars = NULL,
  block2_vars = NULL,
  block3_vars = NULL,
  phonetic_vars = NULL,
  phonetic_method = "soundex",
  birth_year_col = NULL,
  postcode_col = NULL
)

Arguments

data

A data frame that has been processed by clean_the_nest(). Must contain the columns referenced by block1_vars / block2_vars / block3_vars.

block1_vars

Character vector of one or more column names to combine into the primary blocking variable (block1). Single element = direct use of that column. Multiple elements = concatenated composite key.

block2_vars

Optional character vector for a second blocking variable (block2). Use a second, independent variable to allow murmuration() to be run twice with different blocks and results merged — the standard multi-pass blocking strategy to improve recall. NULL (default) suppresses block2.

block3_vars

Optional character vector for a third blocking variable (block3). NULL (default) suppresses block3.

phonetic_vars

Optional character vector of name columns to encode phonetically. Each column x generates a new column x_soundex. These can then be referenced in block1_vars / block2_vars / block3_vars. Requires the phonics package.

phonetic_method

One of "soundex" (default) or "metaphone". Applied to all columns in phonetic_vars.

birth_year_col

Optional name of a Date column from which birth year is extracted. If supplied, a birth_year integer column is added, which can be referenced in composite blocking keys.

postcode_col

Optional name of a postcode column. If supplied, the first 3 digits are extracted as postcode3 (broad geographic blocking).

Details

## Blocking strategy guidance

The goal of blocking is to be broad enough to keep true matches in the same block, and narrow enough to avoid exploding the number of candidate pairs. Practical guidance for Australian surveillance linkage:

Block Recommended variable Notes
Primary "gender" Near-universal; halves the candidate space immediately
Secondary "postcode" or "postcode3" Good geographic signal; use postcode3 if postcode completeness is low
Tertiary Soundex of lettername2 Catches surname spelling variants; do not use as the sole block

Multi-pass blocking (running murmuration() separately with block1 and block2 then unioning results) substantially improves recall at modest computational cost. This is the recommended approach for large datasets (> 100 000 records in either dataset).

## Why not block on Medicare number?

Medicare number is an excellent comparison variable but a poor blocking variable: missing or transcription-error values will split a true pair across blocks, causing them to never be compared. Use Medicare as a compare_var in murmuration(), and as a component of a composite block only when completeness is verified (e.g. > 95% non-missing in both datasets).

Value

The input data frame with new columns appended:

block1

Primary blocking key (always present).

block2

Secondary blocking key (if block2_vars supplied).

block3

Tertiary blocking key (if block3_vars supplied).

<col>_soundex or <col>_metaphone

Phonetic encoding columns (if phonetic_vars supplied).

birth_year

Integer birth year (if birth_year_col supplied).

postcode3

First 3 digits of postcode (if postcode_col supplied).

Original columns are always preserved.

See Also

murmuration, mudnester::clean_the_nest()

Examples

## Not run: 
# Single-field primary block (gender) + postcode secondary block
cases_blocked <- flock(cases_clean,
  block1_vars = "gender",
  block2_vars = "postcode")

# Composite primary block: first letter of surname + gender
cases_blocked <- flock(cases_clean,
  block1_vars  = c("lettername2_initial", "gender"),
  block2_vars  = "gender",
  phonetic_vars = "lettername2")

# Full three-pass setup
cases_blocked <- flock(cases_clean,
  block1_vars   = "gender",
  block2_vars   = "postcode3",
  block3_vars   = "birth_year",
  phonetic_vars = "lettername2",
  birth_year_col = "dob",
  postcode_col  = "postcode")

# Then pass to murmuration() separately for each block:
linked1 <- murmuration(cases_blocked, vax_blocked,
  blocking_var = "block1", ...)
linked2 <- murmuration(cases_blocked, vax_blocked,
  blocking_var = "block2", ...)
linked_all <- dplyr::bind_rows(linked1, linked2) |>
  dplyr::distinct(id_var.x, .keep_all = TRUE)

## End(Not run)


Links case, hospital, outbreak, event linelists, vaccination datasets

Description

**Bird note**: A murmuration is one of nature's most arresting phenomena: tens of thousands of starlings moving as a single fluid shape across the sky, with no conductor and no central instruction — each bird responding only to its nearest neighbours until a coherent, shifting pattern emerges from the whole flock. murmuration() works the same way: it takes two separate, uncoordinated datasets and lets pairwise local comparisons between records resolve, through the Fellegi-Sunter EM algorithm, into one coherent linked result. No single record "knows" about the others — the shape emerges from the scoring.

Probabilistic record linkage of two surveillance datasets using the Fellegi-Sunter framework. Links diagnostic case linelists, hospital admission records, outbreak linelists, and event manifests to vaccination history (Australian Immunisation Register) or to each other. Wraps the full reclin2 pipeline — blocking, comparison, EM scoring, threshold selection, and post-linkage window filtering — in a single practitioner- facing call.

Usage

murmuration(
  data_x,
  data_y,
  linkage_type = NULL,
  event_type = NULL,
  method = "probabilistic",
  event_date = NULL,
  id_var,
  blocking_var = NULL,
  compare_vars = NULL,
  threshold_value = 16,
  perch_before_linking = FALSE,
  inspect_matches = FALSE,
  inspect_extra_vars = NULL,
  resume_from_pairs = NULL,
  vax_window = list(days_before = 14, days_after = 0, lookback_days = Inf),
  cohort_window = NULL,
  days_allowed_before_event = 7,
  days_allowed_after_event = 14,
  one_row_per_person = TRUE,
  clean_eggs = TRUE,
  prefix = NULL,
  suffix = NULL,
  days_between_onset_death = 30,
  last_follow_up = NULL,
  keep_pairs_pred = FALSE
)

Arguments

data_x

This is a dataframe object, cleaned using clean_the_nest, and would often represent the base, or "x" dataset (when doing left joins). Typically this would be a dataset of cases, have enough data to create linkages, and have event dates (e.g., onset_date).

data_y

This is a dataframe object, cleaned using clean_the_nest, and would often represent the admissions or vaccination dataset ("y" dataset when doing left joins). Typically this would have enough data to create linkages, and include either admission data or vaccination event data (e.g. Australian Immunization Register). data_x/data_y deliberately match the .x/.y suffixes reclin2's own link() applies to any colliding column name (including id_var itself — see id_var_y in @return below): the naming here isn't arbitrary, it's the same x/y distinction the join engine itself already uses internally.

linkage_type

The linkage to perform. As of starling 1.1.0 the preferred value is "cohort2event" — a single, explicit linkage concept: link a base linelist of people (a "cohort" — cases, hospitalisations, a birth cohort, an outbreak linelist, a flight manifest) to a stream of dated events (a "case" diagnosis, a "hospitalisation", or a "vaccination"), keeping events that fall in a time window relative to an anchor. Pair it with event_type to name the event stream. The window may sit before, during, or after the cohort's follow-up, governed by vax_window (event-relative) or cohort_window (calendar).

Legacy codes: "c2h" and "v2c" still work and route identically, but emit a deprecation warning nudging to the collapsed form: "c2h" (cases->hospitalisations) becomes event_type = "hospitalisation"; "v2c" (->vaccination history) becomes event_type = "vaccination". "v2h" and "v2e" are defunct (an error naming the replacement): "v2h" was event_type = "vaccination" with hospitalisations as data_x, and "v2e" is event_type = "vaccination" with a scalar Date passed to event_date. If NULL (default), "c2h" is assumed for backwards compatibility. When linking to a vaccination dataset, use a single row per person (run the vaccination data through clean_the_nest() with lie_nest_flat = TRUE).

event_type

Required when linkage_type = "cohort2event": names the event stream in data_y. One of "vaccination", "hospitalisation" ("hospitalization" also accepted), or "case". Ignored (with the routing inferred from the code) when a legacy linkage_type is supplied.

method

Linkage engine. "probabilistic" (default) uses the Fellegi-Sunter EM pipeline (reclin2) with fuzzy field comparison and a score threshold — appropriate when identifiers are imperfect and you need weighted, partial-agreement matching. "deterministic" skips EM scoring entirely and links only records whose compare_vars match exactly (all fields, no partial credit). Deterministic linkage is the right choice when you have a clean, reliable composite key (e.g. full name + date of birth, as in Smoll et al. 2023) and want reproducible, explainable, threshold-free links. Under "deterministic": weights is NA (no composite score exists), threshold_value/perch_before_linking are ignored, and a non-unique key in data_y emits a message rather than silently resolving. All linkage types and both window mechanisms work under either method.

event_date

The anchor date used to define the linkage window and determine valid vaccinations or related admissions.

  • Usually: a character string naming any date column present in data_x. Any date column produced by mudnester::clean_the_nest() is valid here — not just "onset_date" or "admission_date". In birth-cohort or coverage studies, pass "cohort_entry_date" to anchor the vaccination window from the start of follow-up, or "cohort_exit_date" to bound from the end. Examples: "onset_date", "admission_date", "cohort_entry_date", "cohort_exit_date".

  • For a fixed-date event (event_type = "vaccination" only): a single Date object (e.g., as.Date("2024-12-15")) representing a fixed event date shared across all records (e.g. a flight, an outbreak event).

This parameter is critical for determining valid vaccinations (must occur before event_date - days_allowed_before_event) and for "c2h" linkages, determining disease-related admissions.

id_var

Variable name (e.g. "id"). This is critical for data-linkage and the base dataset is the dataset you would left join onto (e.g. the "x" dataset). Cannot have missing data, or the observation will be lost in the linking process.

blocking_var

Variable name (e.g. "block2"). Choice of blocking variable. Use flock() to automatically construct up to three blocking variables (coarse, medium, fine) from standardised linkage fields — it produces columns named block1, block2, block3 by default. You can also create your own. Choose a broader/looser variable (e.g. gender) for small datasets or low data quality, and a finer variable (e.g. postcode + DOB year) for large, high-quality datasets. Required unless resume_from_pairs is used, in which case blocking has already happened and this is ignored.

compare_vars

Vector of variables. Used to compare variables between each dataset and calculate the string score differences. Typically names, dates of births and medicare/social security numbers. Required unless resume_from_pairs is used, in which case comparing has already happened and this is ignored.

threshold_value

Numeric, default 16. The Fellegi-Sunter log-likelihood ratio score at or above which a pair is classified as a match. The score is dataset-specific — there is no universal correct value. Use murmuration_plot to inspect your score distribution and select a threshold that sits in the natural valley between the match and non-match peaks — pass this function's own return value straight into it (call this function with keep_pairs_pred = TRUE first; see that argument), no need to re-derive the pairs table. Higher values increase specificity (fewer false links); lower values increase sensitivity (fewer missed true matches). The default of 16 assumes 5 compare_vars with an agreeing Medicare number (see "On threshold selection" above): with 3 or 4 fields, or an incomplete Medicare field, the valley usually sits much lower. Re-derive the threshold via murmuration_plot whenever compare_vars' length changes — don't carry a threshold forward from a differently-sized comparison set (see Troubleshooting, cause 2, below).

perch_before_linking

Logical. If TRUE, calls perch on the scored pairs immediately after the EM algorithm fits and before the threshold is applied, printing a sensitivity table showing match counts and clerical burden across the score range. In interactive sessions the plot is also displayed. In non-interactive sessions (e.g. Quarto render, batch jobs) only the table is printed and execution continues automatically. Default FALSE.

inspect_matches

Logical. If TRUE, stops immediately after blocking and EM scoring and returns the full candidate-pairs table for manual review, instead of proceeding to threshold selection, link(), or any linkage_type-specific event-window filtering. Requires method = "probabilistic". Unlike the plain pairs_pred attached elsewhere, this table has the actual id_var and compare_vars field values joined in from both sides (suffixed .x/.y), so a specific pair can be read and judged, not just indexed. A mechanical threshold column (weights >= threshold_value) and an empty match_override column (NA/"match"/"non-match", for you to fill in on individual pairs after inspection) are included. event_date is not required when this is TRUE, since the event-window stage that needs it is never reached. Pass the result straight to murmuration_plot to see the score distribution. Default FALSE.

inspect_extra_vars

Character vector of additional column names (present in both data_x and data_y) to join into the inspect_matches review table beyond id_var and compare_vars – e.g. a field you want visible for context while reviewing but did not include in the linkage key itself. Ignored unless inspect_matches = TRUE. Default NULL.

resume_from_pairs

A reviewed pairs table – normally the object returned by murmuration(inspect_matches = TRUE), optionally with its match_override column edited (NA/"match"/"non-match") – to resume the linkage from, skipping blocking, comparing, and EM-fitting entirely. blocking_var and compare_vars are not needed in this mode. data_x/data_y must be the exact same data frames used to produce it (a row-count check guards against an obvious mismatch, but cannot catch every case) – .x/.y are row indices into them. Mutually exclusive with inspect_matches. threshold_value still applies here, to any pair whose match_override is NA – it does not have to match what was used when inspect_matches built this table. Default NULL.

vax_window

A named list defining the vaccination validity window relative to event_date. Used for every vaccination linkage (event_type = "vaccination"). Contains up to three elements:

days_before

Minimum days before event_date a vaccine must have been administered to count as prior valid exposure. Vaccines administered within this buffer (i.e. fewer than days_before days before the event) are excluded because they may not yet have conferred protection. Default 14. Set to 0 if you want all prior vaccinations regardless of recency (e.g. birth-cohort studies where protection is assumed immediate).

days_after

Maximum days after event_date to retain a vaccination record. Default 0 (no post-event vaccinations retained). Set to a positive value to capture post-event vaccination – useful for studying vaccination uptake following a diagnosis or intervention (e.g. 365 to capture all vaccinations in the year after diagnosis). Post-event doses are kept in the vax_date_<n> columns like any other valid dose; compare them with event_date downstream if pre- and post-event doses need separating.

lookback_days

Maximum days before event_date to look back for valid vaccinations. Default Inf (no upper lookback limit – any prior vaccination regardless of age counts). Set to 365 to restrict to vaccinations in the past year only (appropriate for annual influenza VE studies where a vaccine from five years ago is not the relevant exposure).

Example: vax_window = list(days_before = 14, days_after = 0, lookback_days = 365) retains only vaccinations that occurred 14 or more days before the event and within the past year, excluding both too-recent and too-old doses.

Overridden by cohort_window when both are supplied. For "c2h" linkages, use days_allowed_before_event and days_allowed_after_event instead (those govern the admission window, not vaccination).

cohort_window

An optional named list defining a calendar-based observation window that replaces vax_window when supplied. Use this for cohort studies, coverage analyses, or any design where the observation window is defined at the study level rather than relative to individual event dates:

entry

A Date object (or character coercible to Date via as.Date()) giving the start of the observation window. Vaccinations before this date are excluded. Example: as.Date("2024-01-01").

exit

A Date object giving the end of the observation window. Vaccinations after this date are excluded. Example: as.Date("2024-12-31").

When cohort_window is supplied, vax_window is ignored entirely and a message is emitted confirming which window is active. Useful when the event date is unknown, unreliable, or irrelevant to the vaccination exposure definition (e.g. a prevalence survey, a screening programme evaluation, or a birth-cohort study anchored to a fixed follow-up period rather than individual birth dates). Can be used with any linkage_type.

days_allowed_before_event

Numeric. For "c2h" linkages only: the lower bound of the disease-related admission window – how many days before event_date an admission may still be considered disease-related. Default 7. Not used for vaccination linkage types; use vax_window$days_before for those.

days_allowed_after_event

Numeric. For "c2h" linkages only: the upper bound of the disease-related admission window – how many days after event_date an admission may still be considered disease-related. Default 14. Not used for vaccination linkage types; use vax_window$days_after for those.

one_row_per_person

Logical (TRUE or FALSE) with the default being TRUE. It will take multiple admissions per person, and create a series of variables prefixed with "first_", such as "first_admission_date", and put into a single row all admission events, and create a series of variables suffixed with "s", such as "admission_dates". Will work with single admissions per person.

clean_eggs

Logical (TRUE or FALSE) with the default being TRUE. Drops all the .y variables that are duplicates of the second dataset (data_y), and keeps the variables and removes the .x from data_x. If you leave this on, many, if not most variables will have ".x" or ".y" attached to them (e.g. gender) and thus keep this as TRUE for default, and FALSE if you want to check the linkages are true and working.

prefix, suffix

Character or NULL (default NULL for both – every existing call is unaffected unless you supply one). Text added to every column murmuration() contributes from data_y or computes about the link itself (weights, threshold, and every derived column the relevant linkage_type block produces – e.g. vaccination_status, total_vax, first_vax_date, first_vax_type, last_vax_date, last_vax_type, a colliding identifier from data_y's side). data_x's own columns are never touched – id_var in particular stays plain and stable, which is what makes it a reliable join key afterwards. If both are supplied, prefix is applied first, then suffix.

Built for linking one origin dataset against several separate event-stream datasets in independent calls – e.g. a cohort against flu, COVID, RSV, and shingles vaccination registries – where every call would otherwise produce the same generic column names (weights, vaccination_status, ...) and collide the moment you try to combine the results:

  flu_linked   <- murmuration(cohort, flu_vax,   ..., suffix = "_flu")
  covid_linked <- murmuration(cohort, covid_vax, ..., suffix = "_covid")
  rsv_linked   <- murmuration(cohort, rsv_vax,   ..., suffix = "_rsv")

  master <- cohort |>
    dplyr::left_join(dplyr::select(flu_linked,   id_var, ends_with("_flu")),   by = "id_var") |>
    dplyr::left_join(dplyr::select(covid_linked, id_var, ends_with("_covid")), by = "id_var") |>
    dplyr::left_join(dplyr::select(rsv_linked,   id_var, ends_with("_rsv")),   by = "id_var")
  

No manual select()/rename() step is needed between each murmuration() call and the join, and each call stays fully independent – none of them ever needs a previous call's result as input, so there is nothing accumulated for column names to collide with in the first place.

days_between_onset_death

Numeric (e.g. "30"). If you have put a date of death into the clean_the_nest command (which will rename it to dod), then the command will find disease related dates of death. This is chosen number of days between event_date and death for a disease-related death. Often this may be 30 days for SARS-CoV-2 or can be much longer for HIV. If you don't want an upper limit, use "9999".

last_follow_up

Represents a date (input as ymd(2024-11-22)) that represents last follow-up. This could be the latest admission date of a dataset. Used for calculating survival time.

keep_pairs_pred

Logical. If TRUE, attach the full candidate-pairs scoring table as attr(x, "pairs_pred") on the returned data frame (see @return below) – needed for murmuration_plot's score distribution, or for pulling the table out directly. Default FALSE: OPT-IN, not opt-out. This table is every candidate pair blocking produced, before thresholding – confirmed in practice to reach tens of millions of rows for a single call against a large data_y, and it is serialised in full by saveRDS() along with everything else on the returned object, not just held in memory for the duration of the call. Leave at FALSE unless you specifically need murmuration_plot() or attr(x, "pairs_pred") for THIS call – re-run just that one call with keep_pairs_pred = TRUE when you do, rather than defaulting it on everywhere. Does not affect inspect_matches = TRUE, which already returns the full pairs table directly as its return value – an already-explicit request, not governed by this argument.

Details

Make sure that you do not have the same variables (other than linkage variables e.g. letternames, DOB, gender) in both datasets. Always make sure your date columns are properly formatted using as.Date(). For example, if both datasets have a date of death, choose the dataset with the highest confidence and drop the date of death from the other before linking. If linking to a hospitalisation dataset, the difference between event_date and admission_date is used to identify disease-related admissions; unrelated hospitalisations can be filtered separately using ICD-10 codes or AR-DRG codes prior to linkage.

The recommended pre-linkage workflow is:

  1. mudnester::clean_the_nest() to clean and prep data for linkage. Pay close attention to your linkage variables (letternames, date of birth, medicare number, gender and/or postcode), and ensure all dates are formatted as dates.

  2. linkage_quality() to run a structured battery of pre-linkage quality checks across both datasets (completeness, duplicates, Medicare validity, date plausibility, gender and DOB year distribution).

  3. check_medicare to validate Medicare check digits and flag invalid numbers before they enter comparison scoring.

  4. flock() to create up to three blocking variables at different specificity levels (coarse, medium, fine) — pass one to the blocking_var argument below.

  5. murmuration with linkage_type = "cohort2event", event_type = "vaccination" to link cases (or any cohort – hospitalisations for a test-negative design, a birth cohort) to vaccination data, anchored on a date column of data_x.

  6. murmuration with linkage_type = "cohort2event", event_type = "hospitalisation" to link cases to hospital admissions.

  7. murmuration with linkage_type = "cohort2event", event_type = "vaccination" and a single Date as event_date to link event linelists (flight manifests, outbreak investigations) to vaccination history as at that date.

  8. murmuration_plot, called directly on this function's own return value (pass keep_pairs_pred = TRUE to the murmuration call above first — default FALSE skips building this table), to visualise the full linkage score distribution (jittered by blocking_var) and confirm the threshold before accepting the linked dataset. No need to re-derive the pairs table via reclin2 yourself.

  9. mudnester::preening() to prettify the dataframe prepping it for exploration, analysis and presentation. Great to use with gtsummary::tbl_summary().

## On threshold selection The threshold_value is a Fellegi-Sunter log-likelihood ratio score and is dataset-specific — there is no universal correct value. The default of 16 is calibrated against SCPHU datasets with 5 comparison variables (first name, last name, date of birth, Medicare number and gender or postcode) where the Medicare number is present and current on both sides. Use murmuration_plot (after calling this function with keep_pairs_pred = TRUE) to inspect the bimodal score distribution from your specific dataset and identify the natural valley between the match and non-match peaks. Typical working ranges: conservative (high specificity) about 20-25; balanced (default) about 14-18; sensitive (high recall) about 8-13.

Reminder: 16 is calibrated for 5 compare_vars with an agreeing Medicare number – it is not a safe default otherwise. Fewer variables (e.g. AIR-style vaccination extracts with no address field, often down to 3) structurally cap the achievable weight below what 16 assumes, which reads as "zero links" even when the underlying data is fine. A Medicare number that is missing on one side, or recorded from an older card (the 10th digit is the card issue number and changes every time a card is replaced), removes most of that field's weight, so those true matches form a second, lower cluster that 16 can cut off entirely – see vignette("threshold-selection", package = "starling"), which measures recall for 3, 4 and 5 comparison variables. Comparing on medicare09 (account plus check digit) instead of medicare10 avoids the card-issue penalty. Treat a change in compare_vars – or in how complete your Medicare field is – as a reason to re-plot and re-choose the threshold, not just a reason to re-run the same call.

## Phonetic-key deterministic matching method = "deterministic" requires every compare_vars field to match exactly — by design, it has no tolerance for typos or transcription variants the way method = "probabilistic" does. A common way to add tolerance back in, without moving to probabilistic scoring at all, is to match on a phonetic code instead of the literal string: "Smith"/"Smyth" or "Catherine"/"Kathryn" produce the same Soundex/Metaphone code even though the literal strings differ, so an exact match on the code tolerates exactly this kind of spelling variation while remaining fully deterministic — no scoring, no threshold, same as any other deterministic key.

This needs no change to murmuration() itself — flock() already generates the phonetic codes required, via its phonetic_vars/ phonetic_method = "soundex" or "metaphone" arguments, appending a <col>_soundex/<col>_metaphone column. Prepare both datasets before calling this function, then compare on the phonetic column instead of the literal name field:

data_x_phon <- flock(data_x, phonetic_vars = c("lettername1", "lettername2"),
                   phonetic_method = "metaphone")
data_y_phon <- flock(data_y, phonetic_vars = c("lettername1", "lettername2"),
                   phonetic_method = "metaphone")

murmuration(data_x_phon, data_y_phon,
  method       = "deterministic",
  compare_vars = c("lettername1_metaphone", "lettername2_metaphone", "dob"),
  ...)

Double Metaphone is generally preferred over Soundex when initial-letter/sound variation is common, since Soundex keeps the first letter of the string literal — see flock's own documentation for the full comparison.

This trades precision for recall in a specific, controllable way: it will now count "Smith"/"Smyth" as identical, but it will also count some genuinely different names that happen to share a phonetic code as identical (both Soundex and Metaphone have known false-positive pairs). Reserve it for fields where transcription variation is the dominant error mode you're trying to catch, not as a general replacement for exact matching across every field — most linkages benefit from phonetic tolerance on name fields specifically, while keeping dob/postcode/medicare as ordinary exact matches. See Example 11 below for a complete worked version.

## Linking one cohort to several event streams A common design is linking a single origin dataset (a cohort, a dialysis register, a birth cohort) against several separate event-stream datasets in independent calls — one call per vaccine type, for instance, rather than one call with several events mixed together. Every call produces the same generic column names (weights, vaccination_status, total_vax, ...) regardless of which event stream it linked, which collide the moment more than one call's result needs to sit in the same data frame. prefix/suffix solve this at the source — see their documentation below and Example 9 — rather than requiring a manual select()/rename() pass on each call's output before joining. Keep each call independent (against the origin dataset directly, never chaining one call's result into the next as data_x) and combine the results afterwards with dplyr::left_join() on id_var, which prefix/suffix never touch.

## Troubleshooting: zero (or unexpectedly few) links Five real, previously-encountered causes, not a theoretical list. The first three affect the score a genuine pair receives; the fourth stops candidate pairs from being formed at all, upstream of scoring; the fifth is specific to vaccination-type linkage. Run preflight before linking — it catches most of causes 1 and 3 up front. After linking, keep_pairs_pred = TRUE plus murmuration_plot (or a bare summary(attr(x, "pairs_pred")$weights)) tells you which kind of zero you have: a scoring problem (plenty of candidate pairs, none score high enough) or a blocking problem (almost no candidates exist to begin with) — the fix is different for each.

  1. Letter-name fields swapped between data_x and data_y. If one dataset's mudnester::clean_the_nest() call maps lettername1 to first name and lettername2 to last name, and the other dataset has them the other way around, every comparison is first-name-to-last-name and vice versa — structurally never a match, however clean the underlying data actually is. Each side looks correct in isolation (it's internally consistent), so this doesn't surface until the two clean_the_nest() calls are checked side by side, field mapping by field mapping.

  2. Too few compare_vars for the threshold_value in use. The maximum achievable Fellegi-Sunter weight rises with the number of comparison fields — a threshold calibrated against 5 compare_vars (this function's default of 16 assumes that many) is often unreachable with 3 or 4, since AIR-style vaccination extracts frequently have no address field to compare. The console output naming this exact combination is "Pairs selected (threshold=TRUE): 0" against a large candidate-pair count — that pairing means the threshold, not the data, is the problem. Lower threshold_value and re-inspect with murmuration_plot rather than concluding the linkage itself failed.

  3. Inconsistent cleaning/encoding between data_x and data_y. Two records that are obviously the same person to a human don't match if one side has gender = "M"/"F" and the other "Male"/"Female", or one side's postcode is numeric and the other's is a zero-padded string. This degrades both compare_vars scoring (cause 2 above) and blocking_var alignment (cause 4 below) at once, since both are built from the same cleaned fields.

  4. blocking_var doesn't mean the same thing on both sides. Blocking keys are literal string concatenations — a block built as gender + postcode on data_x and gender + dob_yr on data_y (or the "same" block built by two flock() calls whose inputs quietly drifted apart over time) never places a true pair in the same block, so they are never even compared, let alone scored. This is a candidate-formation problem, not a scoring one — keep_pairs_pred = TRUE shows a near-zero candidate-pair count, not just a low-scoring one. A blocking_var that's too fine-grained on its own (e.g. exact dob with no coarser fallback) produces the identical symptom for a different reason: every block ends up with exactly one row per side, so there's nothing for a true pair to be compared against.

  5. Vaccination data left in long (one-row-per-dose) format. clean_the_nest(data_type = "vaccination") does not pivot to vax_date_1/vax_type_1, ... on its own — lie_nest_flat = TRUE is required. Without it, the data passes through unpivoted with no error from clean_the_nest() itself; the failure only surfaces here, silently, as a vaccination-type (event_type = "vaccination") linkage that never finds the columns it looks for.

Value

A linked dataset with some new variables. When method = "probabilistic", linkage metadata travels with the returned data frame as attributes, so murmuration_plot can be called directly on it with no need to re-derive anything via reclin2 – except pairs_pred itself, which is only attached when keep_pairs_pred = TRUE (default FALSE, see that argument above):

attr(x, "pairs_pred")

Only present when keep_pairs_pred = TRUE was passed to this call; NULL otherwise (the new default). The full candidate-pairs scoring table (every compared pair, not just the ones that cleared threshold_value), with the realised blocking_var value joined on for each pair.

attr(x, "blocking_var")

The blocking_var value actually used.

attr(x, "threshold_value")

The threshold_value actually used.

attr(x, "murmuration_method")

"probabilistic" or "deterministic".

Under method = "deterministic", pairs_pred is NULL and blocking_var/threshold_value are NA: there is no Fellegi-Sunter score to inspect (deterministic linkage is threshold-free by design – see method above).

When inspect_matches = TRUE, the return shape is different: instead of a linked dataset, you get the candidate-pairs table itself (see inspect_matches above) – there is no linked df yet, because threshold selection and any event-window filtering have not run. The same four attributes are still attached directly to this table (not nested under a separate pairs_pred attribute, since the returned object already is that table).

<id_var>_y (corrected this revision – previously the fixed literal "id_var_df2", and "c2h"-only; now dynamically named the same way id_x_col/id_y_col are internally, and consistent across all four linkage_type routes): the matched data_y record's own id_var value, one row per person after the one_row_per_person collapse – e.g. id_var = "identity" produces a column literally named identity_y. NA for a data_x row with no above-threshold match. This is the only trace of which specific data_y record a person matched to that survives clean_eggs = TRUE (the default) – every other .y-suffixed column from data_y is dropped by that step, by design. Keep it if you need an audit trail back to a specific vaccination dose or hospital admission record; otherwise it's safe to ignore alongside the domain-specific derived columns (vaccination_status, first_admission_date, ...).

Note

Ensure there are no missing vaccination dates in vaccination dataset prior to murmuration. Murmuration requires complete vaccination data (equal date and type columns per observation) to achieve correct matching of vaccination columns. If there are too few variables to match on, then matching will not work well. For example, if you have first name, last name and date of birth, and a very large dataset (Immunization Register), then the scoring will not differentiate true from false matches. Consider deterministic linkage when there is a paucity of information to use to derive linkage scores.

References

Deterministic linkage (method = "deterministic") – Applied. 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. This study's linkage key – full first name (middle names omitted), full last name, and date of birth – across PCR results (NOCS), hospital admissions, and the Australian Immunisation Register is exactly what method = "deterministic" reproduces directly: pass compare_vars = c("lettername1", "lettername2", "dob") to recreate this study's linkage recipe (see Example 3).

Probabilistic linkage (method = "probabilistic") – Precedent. The same Smoll et al. 2023 study is also the methodological precedent for method = "probabilistic": the Fellegi-Sunter approach generalises that study's exact-key design to settings where identifiers are too incomplete or inconsistent for an all-fields-exact match to find every true pair.

Applied. 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. About 10% of this study's birth-register records carried identifier or date-of-birth errors that ruled out an exact match to hospital and immunisation records; these were resolved with weighted-score matching across multiple data points – the situation method = "probabilistic" together with murmuration_plot is built for, where a clean composite key (as in the Smoll et al. 2023 design above) cannot be assumed and the score distribution should be inspected before a threshold is chosen. The birth-cohort linkage in Example 4 below mirrors this study's maternal-neonatal dyad plus vaccination-register design; Example 10 reproduces its two-pathway (nirsevimab/Abrysvo) linkage directly.

Examples

# All eleven examples below are kept as \dontrun{} rather than \donttest{}
# (aviary ecosystem plan \S8.9.2): each illustrates a distinct calling
# convention (linkage_type/event_type routing, threshold selection,
# manual pair review, multi-registry linking) against realistically
# multi-hundred-row blocking -- the score-distribution and threshold
# behaviour these are actually meant to show does not survive shrinking
# to a handful of synthetic rows small enough to embed here, and several
# depend on \pkg{reclin2}'s full pair_blocking()/problink_em() pipeline
# rather than the simpler deterministic exact-join path. See
# \code{\link{murmuration_plot}} for a genuinely runnable \donttest{}
# example against this same package's plotting function.
## Not run: 
# Example 1: Link cases to vaccination history (onset_date as anchor),
# using the current preferred interface (linkage_type = "cohort2event" +
# event_type) introduced in starling 1.1.0.
dx_clean <- clean_the_nest(dx_data,
  data_type = "cases",
  id_var = "identity",
  lettername1 = "first_name",
  lettername2 = "surname",
  dob = "date_of_birth",
  gender = "gender",
  postcode = "postcode",
  medicare = "medicare_no",
  diagnosis = "disease_name",
  onset_date = "date_of_onset")

vax_clean <- clean_the_nest(vax_data,
  data_type = "vaccination",
  id_var = "patient_id",
  lettername1 = "firstname",
  lettername2 = "last_name",
  dob = "birth_date",
  gender = "gender",
  postcode = "postcode",
  medicare = "medicare_number",
  vax_type = "vaccine_delivered",
  vax_date = "service_date")

data_x <- murmuration(dx_clean, vax_clean,
  linkage_type = "cohort2event",
  event_type   = "vaccination",
  event_date = "onset_date",
  id_var = "identity",
  blocking_var = "gender",
  compare_vars = c("lettername1", "lettername2", "dob"),
  clean_eggs = FALSE)
# Legacy equivalent (still works, but emits a deprecation warning):
#   murmuration(dx_clean, vax_clean, linkage_type = "v2c", ...)

# Example 2: Link hospitalization data to vaccination history (admission_date as anchor)
hosp_clean <- clean_the_nest(hosp_data,
  data_type = "hospital",
  id_var = "patient_id",
  lettername1 = "firstname",
  lettername2 = "last_name",
  dob = "birth_date",
  gender = "sex",
  postcode = "zip_codes",
  medicare = "medicare_number",
  admission_date = "date_of_admission",
  discharge_date = "date_of_discharge")

data_y <- murmuration(hosp_clean, vax_clean,
  linkage_type = "cohort2event",
  event_type   = "vaccination",
  event_date = "admission_date",
  id_var = "patient_id",
  blocking_var = "gender",
  compare_vars = c("lettername1", "lettername2", "medicare10", "dob"),
  clean_eggs = FALSE,
  one_row_per_person = TRUE)
# The hospitalisations are simply the cohort here (data_x); this replaces the
# defunct linkage_type = "v2h".

# Example 3: Link cases to hospitalisations (onset_date as anchor) --
# method = "deterministic" reproducing Smoll et al. 2023's exact linkage
# recipe (see @references): full first name, full last name, and date of
# birth, linking 1 Jan-31 Mar 2022 NOCS PCR results to Central Queensland
# hospital admissions. The paper defines a COVID-19-related admission as
# ICD-10-AM B97.2 within 30 days of diagnosis (no pre-diagnosis allowance
# is described in the paper, hence days_allowed_before_event = 0 here --
# widen this if your own admissions data can genuinely precede diagnosis,
# e.g. a PCR test taken during an already-in-progress admission).
# Reported result: 47/9,682 adults hospitalised (0.48%); vaccine
# effectiveness 69.9% for a primary course alone, 81.8% with a booster.
det_linked <- murmuration(dx_clean, hosp_clean,
  linkage_type = "cohort2event",
  event_type   = "hospitalisation",
  method       = "deterministic",
  event_date = "onset_date",
  id_var = "identity",
  blocking_var = "postcode",
  compare_vars = c("lettername1", "lettername2", "dob"),
  days_allowed_before_event = 0,
  days_allowed_after_event = 30,
  clean_eggs = FALSE)
# Legacy equivalent (still works, but emits a deprecation warning):
#   murmuration(dx_clean, hosp_clean, linkage_type = "c2h", method = "deterministic", ...)

# Example 4: Birth-cohort study — cohort_window approach, reproducing the
# observation window of Roughan et al. 2026 (see @references): all 5,116
# infants born at Sunshine Coast University Hospital, 1 May 2024-31 Oct
# 2025. Captures any vaccination administered during the defined follow-up
# period, regardless of individual event dates. That study resolved its
# messier ~10% of birth-register records (identifier/DOB errors) with
# weighted-score matching rather than an exact key -- exactly the case
# method = "probabilistic" (and murmuration_plot(), Example 7 below) is
# built to support. Reported result: 71.7% (3,669/5,116) received valid
# RSV immunisation.
cohort_clean <- clean_the_nest(birth_cohort_data,
  data_type = "cases",
  id_var = "baby_id",
  lettername1 = "first_name",
  lettername2 = "last_name",
  dob = "babys_date_of_birth",
  gender = "sex")

df_cohort <- murmuration(cohort_clean, vax_clean,
  linkage_type  = "cohort2event",
  event_type    = "vaccination",
  event_date    = "dob",
  id_var        = "baby_id",
  blocking_var  = "gender",
  compare_vars  = c("lettername1", "lettername2", "dob"),
  cohort_window = list(
    entry = as.Date("2024-05-01"),
    exit  = as.Date("2025-10-31")
  ),
  clean_eggs = FALSE)

# Example 4b: Annual influenza VE study — 1-year lookback, 14-day buffer.
# Only vaccinations in the 12 months before onset, and >= 14 days before onset,
# are retained as valid prior exposure.
df_flu_ve <- murmuration(cases_clean, vax_clean,
  linkage_type = "v2c",
  event_date   = "onset_date",
  id_var       = "identity",
  blocking_var = "gender",
  compare_vars = c("lettername1", "lettername2", "dob", "medicare10"),
  vax_window   = list(
    days_before   = 14,
    days_after    = 0,
    lookback_days = 365
  ),
  clean_eggs = FALSE)

# Example 4c: Post-diagnosis vaccination uptake study.
# Retains vaccinations up to 1 year AFTER diagnosis as well as valid prior doses;
# compare each vax_date_<n> with onset_date to separate pre- from post-event doses.
df_post_dx <- murmuration(cases_clean, vax_clean,
  linkage_type = "v2c",
  event_date   = "onset_date",
  id_var       = "identity",
  blocking_var = "gender",
  compare_vars = c("lettername1", "lettername2", "dob", "medicare10"),
  vax_window   = list(
    days_before   = 14,
    days_after    = 365,
    lookback_days = Inf
  ),
  clean_eggs = FALSE)

# Example 5: Link flight manifest to vaccination history (fixed event Date object)
manifest_clean <- clean_the_nest(manifest_data,
  data_type = "cases",
  id_var = "passenger_id",
  lettername1 = "first_name",
  lettername2 = "surname",
  dob = "date_of_birth",
  gender = "gender")

df_flight <- murmuration(manifest_clean, vax_clean,
  linkage_type = "cohort2event",
  event_type   = "vaccination",
  event_date = as.Date("2024-03-15"),   # a single Date: the fixed-date event path
  id_var = "passenger_id",
  blocking_var = "gender",
  compare_vars = c("lettername1", "lettername2", "dob"),
  vax_window = list(days_before = 14, days_after = 0, lookback_days = Inf),
  clean_eggs = FALSE)
# Replaces the defunct linkage_type = "v2e".

# Example 6: Link outbreak linelist to vaccination history (fixed event Date object)
linelist_clean <- clean_the_nest(linelist_data,
  data_type = "cases",
  id_var = "case_id",
  lettername1 = "first_name",
  lettername2 = "surname",
  dob = "date_of_birth",
  gender = "gender",
  postcode = "postcode",
  medicare = "medicare_no",
  onset_date = "onset_date")

df_outbreak <- murmuration(linelist_clean, vax_clean,
  linkage_type = "cohort2event",
  event_type   = "vaccination",
  event_date = as.Date("2024-06-01"),
  id_var = "case_id",
  blocking_var = "postcode",
  compare_vars = c("lettername1", "lettername2", "dob", "medicare10"),
  vax_window = list(days_before = 7, days_after = 0, lookback_days = Inf),
  clean_eggs = FALSE)

# Examples 7-9 below continue to use the legacy "v2c" code for brevity, since
# the point of each is the surrounding workflow (threshold inspection, manual
# review, multi-registry linking) rather than the linkage_type argument itself.
# Substitute linkage_type = "cohort2event", event_type = "vaccination" in any
# of them if you are starting a fresh script.

# Example 7: Inspect the linkage score distribution before committing to a
# threshold, in the spirit of Roughan et al. 2026 (@references) — that study
# did not assume its composite key would always match exactly, and resolved
# its messier ~10% of birth-register records with weighted-score matching
# instead.
linked <- murmuration(cohort_clean, vax_clean,
  linkage_type  = "v2c",
  event_date    = "dob",
  id_var        = "baby_id",
  blocking_var  = "gender",
  compare_vars  = c("lettername1", "lettername2", "dob"),
  threshold_value = 16,
  clean_eggs = FALSE,
  keep_pairs_pred = TRUE)   # needed for murmuration_plot()/attr() below --
                            # default FALSE would leave pairs_pred as NULL

# murmuration_plot() runs directly off this return value — no need to hand-roll
# the reclin2 pipeline (pair_blocking() -> compare_pairs() -> problink_em() ->
# predict()) just to see the score distribution. threshold_value and
# blocking_var are picked up automatically from attr(linked, ...).
murmuration_plot(linked)

# Try a different threshold without re-running murmuration():
murmuration_plot(linked, threshold = 14)

# The pairs-level scoring table is also available directly if you need it:
pp <- attr(linked, "pairs_pred")

# Example 8: Manual review of borderline pairs before finalising. Useful
# when murmuration_plot() shows an above-threshold count that doesn't
# match independent expectations (e.g. 79 candidate matches where only 76
# are plausible) and you need to see WHICH pairs are in question, not just
# how many.
review <- murmuration(cohort_clean, vax_clean,
  linkage_type  = "v2c",
  id_var        = "baby_id",
  blocking_var  = "gender",
  compare_vars  = c("lettername1", "lettername2", "dob"),
  threshold_value  = 16,
  inspect_matches  = TRUE)   # event_date not needed for this mode

murmuration_plot(review)   # same plot, run on the full candidate-pairs table

# Pull out the above-threshold pairs with their identifying fields
# (lettername1.x/.y, lettername2.x/.y, dob.x/.y, baby_id.x/.y) for a look:
suspects <- review[review$threshold, ]

# After eyeballing names/DOBs, record a manual decision on specific pairs:
review$match_override[review$baby_id.x == "B0042" &
                       review$baby_id.y == "V0917"] <- "non-match"

# Finish the linkage, respecting that override. data_x/data_y must be the exact
# same data frames used above -- .x/.y are row indices into them.
linked <- murmuration(cohort_clean, vax_clean,
  linkage_type      = "v2c",
  id_var            = "baby_id",
  event_date        = "dob",
  threshold_value   = 16,
  resume_from_pairs = review)

# Example 9: Link one origin cohort against several separate vaccine
# registries (flu, COVID, RSV), each call fully independent -- never
# chaining one call's result into the next -- with suffix distinguishing
# each call's contributed columns so the results can be joined back onto
# the cohort without any manual select()/rename() step in between.
flu_linked <- murmuration(dialysis_cohort, flu_vax,
  linkage_type = "v2c", event_date = "onset_date", id_var = "id_var",
  blocking_var = "gender",
  compare_vars = c("lettername1", "lettername2", "dob"),
  suffix = "_flu")

covid_linked <- murmuration(dialysis_cohort, covid_vax,
  linkage_type = "v2c", event_date = "onset_date", id_var = "id_var",
  blocking_var = "gender",
  compare_vars = c("lettername1", "lettername2", "dob"),
  suffix = "_covid")

rsv_linked <- murmuration(dialysis_cohort, rsv_vax,
  linkage_type = "v2c", event_date = "onset_date", id_var = "id_var",
  blocking_var = "gender",
  compare_vars = c("lettername1", "lettername2", "dob"),
  suffix = "_rsv")

# id_var is untouched by suffix on every call, so it's a stable join key
master_linkage <- dialysis_cohort |>
  dplyr::left_join(dplyr::select(flu_linked,   id_var, ends_with("_flu")),
                    by = "id_var") |>
  dplyr::left_join(dplyr::select(covid_linked, id_var, ends_with("_covid")),
                    by = "id_var") |>
  dplyr::left_join(dplyr::select(rsv_linked,   id_var, ends_with("_rsv")),
                    by = "id_var")

# Example 10: Link a birth cohort to its two separate RSV immunisation
# pathways -- neonatal nirsevimab and antenatal Abrysvo -- reproducing the
# two-pathway design of Roughan et al. 2026 (@references) as two independent
# calls joined via id_var, following the multi-registry pattern in Example 9.
# Reported result: of the 71.7% of infants with valid RSV immunisation,
# 45.2 percentage points came through nirsevimab only and 26.4 through
# Abrysvo only.
#
# Abrysvo is only valid if given >= 14 days before delivery -- vax_window
# captures that floor directly. The paper's additional 28-36-week-gestation
# criterion is a property of the vaccination date itself, not of its distance
# to event_date, so it is not something vax_window can express: check it as
# a separate filter on vax_date/gestational_age after linkage.
abrysvo_linked <- murmuration(cohort_clean, abrysvo_vax,
  linkage_type = "cohort2event", event_type = "vaccination",
  event_date   = "dob",
  id_var       = "baby_id",
  blocking_var = "gender",
  compare_vars = c("lettername1", "lettername2", "dob"),
  vax_window   = list(days_before = 14, days_after = 0, lookback_days = 280),
  suffix       = "_abrysvo")

# Nirsevimab is only valid if given before hospital discharge; discharge
# timing varies per infant, so this is approximated with a short fixed
# post-birth window wide enough to cover a typical birth admission --
# confirm against your own discharge_date field rather than relying on
# this alone.
nirsevimab_linked <- murmuration(cohort_clean, nirsevimab_vax,
  linkage_type = "cohort2event", event_type = "vaccination",
  event_date   = "dob",
  id_var       = "baby_id",
  blocking_var = "gender",
  compare_vars = c("lettername1", "lettername2", "dob"),
  vax_window   = list(days_before = 0, days_after = 10, lookback_days = 0),
  suffix       = "_nirsevimab")

rsv_coverage <- cohort_clean |>
  dplyr::left_join(dplyr::select(abrysvo_linked, baby_id, ends_with("_abrysvo")),
                    by = "baby_id") |>
  dplyr::left_join(dplyr::select(nirsevimab_linked, baby_id, ends_with("_nirsevimab")),
                    by = "baby_id")

# Example 11: Deterministic linkage with phonetic tolerance -- flock() first to
# generate metaphone codes, then match on those instead of the literal strings
# (see "Phonetic-key deterministic matching" above). No murmuration() argument
# changes at all -- this is purely a data-preparation technique.
dx_phon <- flock(dx_clean,
  phonetic_vars   = c("lettername1", "lettername2"),
  phonetic_method = "metaphone")
hosp_phon <- flock(hosp_clean,
  phonetic_vars   = c("lettername1", "lettername2"),
  phonetic_method = "metaphone")

phon_linked <- murmuration(dx_phon, hosp_phon,
  linkage_type = "cohort2event",
  event_type   = "hospitalisation",
  method       = "deterministic",
  event_date   = "onset_date",
  id_var       = "identity",
  blocking_var = "postcode",
  compare_vars = c("lettername1_metaphone", "lettername2_metaphone", "dob"),
  clean_eggs   = FALSE)
# Catches "Smith"/"Smyth"-style transcription variants that exact-string
# deterministic matching (Example 3) would miss -- at the cost of also
# conflating rarer, genuinely different names sharing a phonetic code.

## End(Not run)

Visualise Linkage Weight Distribution Across Blocking Strata

Description

**Bird note**: When a murmuration peaks, a watcher on the ground sees the flock split momentarily into two layers — the dense, high-altitude core of confirmed companions and the looser, lower-flying fringe of uncertain travellers — before the whole shape resolves again. murmuration_plot() captures exactly that split, and now shows whether it holds up flock by flock: the linkage weight distribution separates into a high-score cluster of likely true matches, a low-score cluster of likely non-matches, and a threshold line between them — broken out by blocking stratum so a threshold that looks fine pooled across the whole dataset can be checked for strata where it quietly performs worse.

Generates a jittered scatter plot of Fellegi-Sunter linkage weights, positioned along the x-axis by the blocking_var stratum each candidate pair belongs to (jittered within each stratum for readability), with a horizontal line marking the chosen threshold and shaded regions distinguishing likely matches from likely non-matches.

Usage

murmuration_plot(
  data,
  threshold = NULL,
  blocking_var = NULL,
  max_levels = 12L,
  weight_col = "weights",
  n_sample = 5000L,
  jitter_width = 0.3,
  point_alpha = 0.35,
  point_size = 1.2,
  show_subtitle = TRUE,
  show_counts = TRUE,
  palette = "sch",
  title = NULL,
  interactive = FALSE,
  pairs_pred = NULL
)

Arguments

data

The object returned by murmuration (preferred) — its attached attr(x, "pairs_pred") is used automatically. Also accepts a bare pairs-level data frame with a weight_col column directly, for a saved pairs_pred object or legacy pairs-scoring output produced outside murmuration().

threshold

Numeric or NULL (default). NULL resolves to attr(data, "threshold_value") — whatever threshold_value was actually passed to murmuration() — falling back to 16 (the murmuration() default) with a message() if that attribute isn't available (e.g. a bare pairs-level data frame was supplied).

blocking_var

Character or NULL (default). Name of the column giving each pair's blocking stratum, used to position points along the x-axis (jittered within each stratum). NULL resolves to attr(data, "blocking_var"); if that's unavailable either, falls back to a single unstratified column with a message() explaining how to enable per-stratum jittering.

max_levels

Integer. If more blocking strata are present than this, max_levels - 1 are shown individually and the rest are pooled into an "Other" column, with a warning(). Any stratum containing at least one above-threshold pair is kept individually first; remaining slots go to the highest-volume zero-match strata — see Details, "Reading the per-stratum layout". This is consistent with the ecosystem's facet-count convention (see bowerbird::roost_plot(facet_by = )). Default 12.

weight_col

Name of the column containing linkage weights. Default "weights".

n_sample

Integer. Maximum number of points to plot, in total. Above-threshold pairs are always kept in full; below-threshold pairs are subsampled proportionally within each blocking stratum to fill whatever budget remains, so small strata aren't swamped out by large ones — see Details, "How points are sampled". Plotting millions of points is slow and uninformative; the below-threshold distribution shape is well-represented by 5,000–10,000 points in total. Default 5000.

jitter_width

Numeric. Horizontal jitter width within each blocking stratum's column. Default 0.3.

point_alpha

Numeric (0–1). Point transparency. Default 0.35.

point_size

Numeric. Point size. Default 1.2.

show_subtitle

Logical. Show the subtitle line (threshold, above/below counts, and the sampling note when applicable)? Default TRUE.

show_counts

Logical. Label each blocking stratum's column with its pair count (n = ...)? Default TRUE.

palette

Character. Colour palette for match/non-match zones: "sch" (Sunshine Coast HHS greens — default), "default" (teal/coral), or "grey" (greyscale, publication-safe).

title

Optional plot title string. NULL uses a default title.

interactive

Logical. Return a plotly object (TRUE) or a ggplot2 object (FALSE, default).

pairs_pred

Deprecated. Pre-1.2.0 name for data, when it took only a raw pairs-level object. Positional calls (murmuration_plot(pp, ...)) are unaffected by the rename and never need this — it exists solely to catch old calls that named the argument explicitly (pairs_pred = pp), which emit a warning() and are routed to data for now. Will be removed in a future release; update calls to use data instead.

Details

## Running directly off murmuration()'s own output As of starling 1.2.0, murmuration(method = "probabilistic") attaches its full candidate-pairs scoring table to its own return value as attr(x, "pairs_pred"), along with the blocking_var and threshold_value actually used. murmuration_plot() reads all three straight off that object:

linked <- murmuration(data_x, data_y, ..., blocking_var = "gender", threshold_value = 16)
murmuration_plot(linked)                 # threshold and blocking_var picked up
                                          # automatically
murmuration_plot(linked, threshold = 14) # explore a different cutoff without
                                          # re-running murmuration()

There is no need to hand-roll the underlying pairs-scoring pipeline yourself just to see the score distribution. data can also be a bare pairs-level data frame with a weights column directly (a saved attr(x, "pairs_pred"), or output from the legacy raw pairs-scoring workflow) — see data below.

method = "deterministic" linkage has no Fellegi-Sunter score to plot (weights is NA throughout by design — see murmuration): passing its output here is a stop(), not a silent empty plot.

## How points are sampled With large datasets, plotting every candidate pair is slow and not usually any more informative than a representative sample — but a sample taken uniformly across the whole dataset (or even just within each blocking stratum) can be actively misleading here: above-threshold pairs are often a tiny fraction of all candidate pairs — well under 1% is common — and a uniform sample can easily miss every single one of them, making a real, if small, separation look like no separation at all. Sampling is therefore asymmetric:

When this asymmetric sampling is active, the plot subtitle says so explicitly ("every above-threshold pair shown; below-threshold sampled") when show_subtitle = TRUE. Above-threshold points are also drawn larger, more opaque, and as a different shape (a triangle rather than a circle) than below-threshold points, so they stay visible even when very few of them exist against a large background cloud. The header counts (n above/below threshold) are always computed from the complete, unsampled data — only the scatter of individual points is affected by n_sample.

## Reading the per-stratum layout Strata are ordered left to right by how many above-threshold pairs they contain — most first, tapering to zero — rather than by raw size, so where matches actually concentrate is visible at a glance instead of requiring a scan across every column. Ties (typically among strata with no above-threshold pairs at all) are broken by total pair volume, largest first. "Other" is always last, regardless of its own aggregate count, since it is a heterogeneous pool rather than a single meaningful stratum. If max_levels forces some strata to be pooled, any stratum containing at least one above-threshold pair is kept individually in preference to a larger zero-match stratum — see max_levels.

Each blocking stratum (e.g. each level of gender, or each postcode block) gets its own jittered column of points, all sharing the same y-axis and threshold line. A well-behaved threshold shows the same match/non-match separation in every column; a stratum where points cluster near the threshold line, or where the "likely non-match" cloud creeps above it, is a sign that stratum's identifiers are noisier and may need a different blocking_var, additional compare_vars, or a stratum-specific threshold applied via a separate murmuration() call and a manual dplyr::bind_rows().

## Threshold guidance for Australian public health linkage The Fellegi-Sunter weights produced by the EM algorithm are log-likelihood ratios, not fixed absolute scores, so the "right" threshold is dataset-specific. That said, common reference points for Australian population health work (Medicare, 2 names, DOB) are:

| Threshold | Practical meaning | |—|—| | 8–12 | High sensitivity, lower specificity — suitable when recall matters more than precision (e.g. small datasets, rare disease surveillance) | | 12–17 | Balanced — typical starting point for surveillance linkage with a complete variable set (the murmuration() default, 16, assumes 5 comparison variables with an agreeing Medicare number) | | 17–22 | High specificity — suitable when false matches are especially costly (e.g. VE studies where false vaccination attribution biases the estimate) | | > 22 | Very conservative — consider adding clerical review for records in the 17–22 range |

The most principled approach is to look at the weight distribution (this plot) and choose the threshold at the **lowest density point** between the two modes, checked across every blocking stratum in turn rather than only in the pooled picture. If the two modes overlap substantially, your variable set may lack discriminating power for this dataset — see preflight for diagnostic guidance.

Value

A ggplot2 object (interactive = FALSE) or a plotly htmlwidget (interactive = TRUE).

References

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. Applied, illustrative. About 10% of this study's birth-register records carried identifier or date-of-birth errors and were resolved with weighted-score matching rather than an exact key — murmuration_plot() is built for inspecting exactly that situation, checking whether a candidate threshold holds up once messier records are in the mix, rather than accepting a single cutoff on faith. See murmuration for the full @references entry and the deterministic-linkage precedent (Smoll et al. 2023), which has no score distribution to plot here.

See Also

murmuration, preflight

Examples


# Minimal, fully self-contained example: a bare pairs-level data frame
# with just a weights column (e.g. a saved attr(x, "pairs_pred")) -- the
# "Also accepts a bare pairs-level data frame" path documented in @param
# data above -- so this is a genuine, runnable demonstration that needs
# neither murmuration() nor reclin2 to have actually run.
pairs_toy <- data.frame(weights = c(2, 4, 5, 18, 21, 25, 3, 19, 11, 16))
murmuration_plot(pairs_toy, threshold = 16)


## Not run: 
# The following illustrate running directly off murmuration()'s own
# output -- kept as \dontrun{} rather than \donttest{} because they need
# a real reclin2-scored pairs table (via murmuration(method =
# "probabilistic")) to show per-stratum jittering, threshold exploration,
# and asymmetric sampling meaningfully; a handful of synthetic rows would
# not exercise any of that. The \donttest{} example above already
# demonstrates the core plotting function runs correctly end to end.

# Preferred workflow: pass murmuration()'s own output straight in
linked <- murmuration(dx_clean, vax_clean,
  linkage_type = "cohort2event", event_type = "vaccination",
  event_date = "onset_date", id_var = "identity",
  blocking_var = "gender",
  compare_vars = c("lettername1", "lettername2", "dob"),
  threshold_value = 16)

murmuration_plot(linked)                     # threshold + blocking_var automatic
murmuration_plot(linked, threshold = 14)     # explore a different cutoff
murmuration_plot(linked, max_levels = 6)     # collapse a fine blocking_var
murmuration_plot(linked, palette = "grey")   # greyscale for a journal figure
murmuration_plot(linked, interactive = TRUE) # plotly, for Shiny/Quarto HTML

# Advanced: the pairs-level table on its own, saved for later
pp <- attr(linked, "pairs_pred")
murmuration_plot(pp, threshold = 16, blocking_var = "gender")

## End(Not run)


Threshold Sensitivity Analysis for Linkage Score Cutoff Selection

Description

**Bird note**: A starling tests a perch before committing its weight to it — sitting briefly, sensing stability, probing whether this particular spot will hold before deciding to stay or move on. perch() does exactly that to a threshold: it tries every candidate value across your scored pairs and shows you precisely what the linkage looks like at each one — match count, link rate, clerical burden — so you can commit to the perch that holds, informed by the same benchmarks the AIHW, WA Data Linkage Unit, and PHRN use in practice.

Sweeps a range of candidate Fellegi-Sunter threshold values across a scored pairs object and returns a structured sensitivity table with one row per candidate cutoff. Each row reports the number and percentage of pairs that would be accepted or rejected at that threshold, the number falling in a configurable clerical review zone around it, and (if n_records_primary is supplied) the estimated link rate for the primary dataset. Four canonical thresholds are highlighted in the printed table and the plot with annotations from the three key Australian and international linkage authorities — AIHW, WA Data Linkage Unit, and the Population Health Research Network (PHRN).

Call perch() after murmuration_plot confirms your weight distribution is bimodal, to quantify the trade-off at each candidate cutoff, then pass the chosen value to murmuration(threshold_value = ...). If individual borderline pairs need a human eye rather than a single blanket cutoff, use murmuration(inspect_matches = TRUE) to review them, then murmuration(resume_from_pairs = ...) to finish once any needed match_override decisions are recorded.

Usage

perch(
  pairs_pred,
  weight_col = "weights",
  n_records_primary = NULL,
  thresholds = seq(5, 30, by = 1),
  clerical_window = 6,
  highlight_thresholds = c(10, 15, 16, 20),
  report = TRUE,
  plot = TRUE,
  palette = "sch",
  interactive = FALSE
)

Arguments

pairs_pred

A pairs-level data frame with a linkage weight column – normally attr(murmuration(...), "pairs_pred"), but any pairs-level object with the same shape (including raw reclin2 predict.problink_em() output) works too.

weight_col

Character. Name of the numeric linkage weight column. Default "weights" (the column name murmuration uses internally).

n_records_primary

Integer or NULL. Number of records in the primary (data_x) dataset passed to murmuration. When supplied, a link_rate column is added showing the proportion of data_x records that would receive at least one accepted match at each threshold. Default NULL (link rate column omitted).

thresholds

Numeric vector of candidate threshold values to evaluate. Default seq(5, 30, by = 1), covering the full practical range for Australian population health linkage with a complete variable set. Narrow this for targeted comparisons (e.g. seq(14, 22, by = 0.5)).

clerical_window

Numeric. Width of the clerical review zone centred on each threshold value: the band [threshold - clerical_window/2, threshold + clerical_window/2]. Pairs in this band are those that would change classification if the threshold shifted by half the window width — i.e. the marginal cases a human reviewer would be asked to adjudicate in a two-threshold design. Default 6 (matching the AIHW/WADLU convention of a roughly 10-unit clerical zone centred at each candidate threshold).

highlight_thresholds

Numeric vector. Threshold values to mark with [*] in the printed table and with diamond symbols in the plot. Default c(10, 15, 16, 20) — the four canonical reference points from Australian and international linkage guidance (see Details).

report

Logical. If TRUE (default), prints a formatted sensitivity table with reference annotations to the console.

plot

Logical. If TRUE (default), generates and returns a ggplot2 figure (or patchwork composite if n_records_primary is supplied) showing match count and link rate against threshold with AIHW zone shading and reference markers. If FALSE, returns only the data frame invisibly.

palette

Character. Colour palette: "sch" (SCH Evergreen, default), "default" (teal/coral), "grey" (greyscale, publication-safe).

interactive

Logical. If TRUE, returns a plotly htmlwidget with hover tooltips. Requires plotly. Default FALSE.

Details

## Interpreting the output

Use perch() together with murmuration_plot:

  1. murmuration_plot() confirms the weight distribution is bimodal and shows you where the valley between the two clusters lies.

  2. perch() quantifies the match count, link rate, and clerical burden at each candidate cutoff in that valley.

  3. Choose the threshold that best balances precision and recall for your study design (see benchmarks below). If it looks clean, pass it straight to murmuration(threshold_value = ...). If individual borderline pairs need a human eye first, run murmuration(inspect_matches = TRUE) instead, review the candidates (setting match_override where a manual judgement should win), and finish with murmuration(resume_from_pairs = ...).

The n_clerical column is the key diagnostic for threshold placement. A large n_clerical relative to n_above means the threshold sits in a high-density region of the score distribution — a small shift would reclassify many pairs. You want to sit in the valley (low density), not on a slope (high density). If every threshold in your range has a large clerical burden, the two score modes overlap substantially — this is a signal that the variable set or blocking strategy needs revision before threshold selection will be meaningful.

## Australian and international linkage benchmarks

The Fellegi-Sunter weights are log-likelihood ratios and are **dataset-specific** — no universal cutoff exists. These benchmarks from recognised Australian and international linkage authorities inform where to look:

| Threshold | Authority and basis | |—|—| | **10–20 (clerical zone)** | **AIHW and WA Data Linkage Unit (WADLU)**: the established practice is a two-threshold approach with a clerical review zone of roughly 10–20. Pairs above about 20 are auto-accepted as matches; pairs below about 10 are auto-rejected as non-matches; pairs in between are sent for human adjudication. When operating without a dedicated clerical reviewer (as in most routine surveillance settings), the single threshold should sit somewhere in this range, with the direction of error dictated by the study design. | | **About 15–20** | **Population Health Research Network (PHRN)**: no universal cutoff is mandated, but the operational target is a false-match rate below 0.5 | **12–17** | **starling balanced default** — typical starting point for routine surveillance linkage with a complete variable set. | | **17–22** | **High specificity** — appropriate when false matches carry high analytical cost, e.g. vaccine effectiveness studies where falsely attributing vaccination status to an unvaccinated person biases the VE estimate downward. | | **8–12** | **High sensitivity** — suitable for small datasets or rare-disease surveillance where missing a true match is the dominant concern. |

## Note on link rate

The link_rate column approximates the proportion of primary-dataset records (data_x) that would receive at least one accepted match at a given threshold. It counts accepted pairs above threshold rather than unique linked records (one data_x record can appear in multiple pairs), so it is an upper bound on the true link rate. Nonetheless it is useful for spotting the point at which raising the threshold begins to meaningfully reduce coverage — a sharp inflection in the link rate curve often marks the valley between the two score modes.

Value

When plot = FALSE, returns the sensitivity data frame invisibly. When plot = TRUE (default), prints the data frame to the console (if report = TRUE) and returns the plot object. The data frame has one row per threshold value and the following columns:

threshold

Numeric. The candidate cutoff.

n_above

Integer. Pairs with weight \geq threshold (accepted as matches at this cutoff).

n_below

Integer. Pairs with weight < threshold (rejected as non-matches).

pct_above

Numeric. Percentage of all pairs above threshold.

n_clerical

Integer. Pairs in the clerical review zone [threshold - clerical_window/2, threshold + clerical_window/2].

pct_clerical

Numeric. Percentage in the clerical zone.

link_rate

Numeric or NA. Proportion of n_records_primary records that would receive a match. Only populated when n_records_primary is supplied.

reference

Character. Annotation for the four highlighted threshold values; NA for all others.

References

Australian Institute of Health and Welfare. Data linkage services. AIHW, Canberra.

Holman, C.D.J., Bass, A.J., Rouse, I.L. and Hobbs, M.S.T. (1999). Population-based linkage of health records in Western Australia: development of a health services research linked database. Australian and New Zealand Journal of Public Health, 23(5): 453–459. doi:10.1111/j.1467-842X.1999.tb01297.x

Population Health Research Network (2023). PHRN Linkage Guidelines. PHRN, Perth. (PHRN is now Data Connect Australia.)

Fellegi, I. and Sunter, A. (1969). A theory for record linkage. Journal of the American Statistical Association, 64(328): 1183–1210. doi:10.2307/2286061

See Also

murmuration for the linkage step, and for inspect_matches/ resume_from_pairs if individual pairs need manual review before finishing. murmuration_plot for visual weight distribution inspection. preflight for pre-linkage data quality auditing. flock for blocking variable construction.

Examples

## Not run: 
# Standard workflow: score pairs with murmuration(), then perch to find the
# best threshold. No need to hand-roll the reclin2 pipeline -- run
# murmuration() once and use what it already attaches to its own output.
linked <- murmuration(data_x, data_y,
  linkage_type  = "cohort2event", event_type = "vaccination",
  event_date    = "onset_date",
  id_var        = "id_var",
  blocking_var  = "block2",
  compare_vars  = c("lettername1", "lettername2", "dob", "medicare10"),
  threshold_value = 16)
pairs_pred <- attr(linked, "pairs_pred")

# Step 1: inspect the distribution
murmuration_plot(linked)

# Step 2: quantify the trade-off across the plausible range
results <- perch(pairs_pred, n_records_primary = nrow(data_x))

# Step 3: narrow to the AIHW clerical zone for fine-grained inspection
results <- perch(pairs_pred,
  thresholds    = seq(10, 20, by = 0.5),
  n_records_primary = nrow(data_x))

# Get only the data frame (no plot)
tbl <- perch(pairs_pred, plot = FALSE)

# Interactive dual-panel plot for exploratory use
perch(pairs_pred, n_records_primary = nrow(data_x), interactive = TRUE)

# Greyscale for publication figures
perch(pairs_pred, palette = "grey")

# Step 4: happy with 18 instead of 16? No need to re-fit -- re-run
# murmuration() with the new threshold_value directly.
linked <- murmuration(data_x, data_y,
  linkage_type  = "cohort2event", event_type = "vaccination",
  event_date    = "onset_date",
  id_var        = "id_var",
  blocking_var  = "block2",
  compare_vars  = c("lettername1", "lettername2", "dob", "medicare10"),
  threshold_value = 18)

# Step 5 (optional): if individual borderline pairs need a human eye rather
# than a single blanket cutoff -- see murmuration(inspect_matches = TRUE)
# and murmuration(resume_from_pairs = ...) instead of Step 4.

## End(Not run)


Pre-Linkage Data Quality Checks

Description

**Bird note**: Before a long migration, birds enter a physiological state called *hyperphagia* — they systematically assess and load up on resources, checking body condition before committing to the journey. preflight() is that pre-migration check for your data: a structured, systematic audit of both datasets before committing to probabilistic linkage with murmuration(). Skipping it is like a shorebird launching across the Pacific without first checking its fat reserves.

Runs a battery of pre-linkage data quality checks on two datasets and returns a structured report. Checks cover: completeness of linkage variables, date plausibility, uniqueness of identifier columns, consistency of factor levels across datasets (e.g. gender coding), Medicare validity (if present), name length and character distribution, duplicate record detection, and dataset overlap summaries. Optionally runs check_medicare if a Medicare column is identified.

The report is printed to the console and returned invisibly as a named list so it can be saved, embedded in a Quarto report, or passed to downstream checks.

Usage

preflight(
  data1,
  data2,
  linkage_vars = NULL,
  id_col1 = "id_var",
  id_col2 = "id_var",
  blocking_vars = NULL,
  date_cols = NULL,
  medicare_col = NULL,
  name_cols = NULL,
  min_name_length = 2L,
  verbose = TRUE
)

Arguments

data1

First data frame (typically the case/index dataset, data_x in murmuration()).

data2

Second data frame (typically the vaccination/hospitalisation dataset, data_y in murmuration()).

linkage_vars

Character vector of column names that will be used as compare_vars in murmuration(). These are the variables preflight() will assess most carefully.

id_col1

Name of the unique record identifier in data1. Default "id_var".

id_col2

Name of the unique record identifier in data2. Default "id_var".

blocking_vars

Character vector of planned blocking variable names to check for completeness. If NULL (default), blocking variables are not checked.

date_cols

Character vector of date column names to check for plausibility (no future dates, no dates before 1900). NULL (default) skips date checks.

medicare_col

Name of the Medicare number column if present and to be validated. NULL (default) skips Medicare validation. If supplied, check_medicare is run on both datasets and results summarised here.

name_cols

Character vector of name columns to check for short strings (potential initials or truncations), all-numeric entries, and excessive punctuation. Default checks "lettername1" and "lettername2" if present.

min_name_length

Integer. Names shorter than this are flagged as potentially truncated or coded. Default 2.

verbose

Logical. Print the full report to console? Default TRUE.

Value

Invisibly, a named list with the following elements:

completeness

A data frame: variable, dataset, n_present, n_missing, pct_missing for each linkage variable.

duplicates

A data frame: dataset, n_records, n_unique_ids, n_duplicate_ids, pct_duplicate.

blocking_completeness

Completeness of blocking variables, or NULL if not checked.

date_checks

Date plausibility results, or NULL if not checked.

medicare

Medicare validity results from check_medicare(), or NULL if not checked.

name_checks

Name quality results, or NULL if not checked.

factor_consistency

Comparison of factor levels for shared categorical columns.

overlap_summary

Approximate overlap statistics for key demographic variables.

flags

Character vector of warning-level flags raised during the checks. Empty if no issues found.

See Also

check_medicare, murmuration, flock

Examples

## Not run: 
# Basic pre-flight check before v2c linkage
report <- preflight(
  data1         = cases_clean,
  data2         = vax_clean,
  linkage_vars  = c("lettername1", "lettername2", "dob", "medicare10"),
  id_col1       = "id_var",
  id_col2       = "id_var",
  blocking_vars = "gender",
  date_cols     = c("dob", "onset_date"),
  medicare_col  = "medicare"
)

# Access the completeness table programmatically
report$completeness

# Save the report to a CSV for documentation
write.csv(report$completeness, "preflight_completeness.csv", row.names = FALSE)

## End(Not run)