| 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 |
| 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
-
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. -
check_medicare()— Validate Medicare numbers using the Services Australia Modulus 10 weighted checksum (can also be called standalone or frompreflight()). -
flock()— Generate blocking variables (single-field, phonetic, or composite) to partition records before linkage. -
murmuration()— Link a cohort to a dated event stream (linkage_type = "cohort2event"with anevent_typeof"vaccination","hospitalisation", or"case"), using eithermethod = "probabilistic"(Fellegi-Sunter EM via reclin2) ormethod = "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 ofcohort2event; vaccination-to-hospitalisation ("v2h") and vaccination-to-event ("v2e") are defunct as of 2.0.0 (usecohort2eventwithevent_type = "vaccination", and a fixedevent_datefor an event linelist). -
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 tomethod = "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:
Nicolas Smoll nicolas.smoll@health.qld.gov.au (ORCID)
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 |
output_col |
Character. Name of the new validation flag column added to
|
verbose |
Logical. If |
keep_digits |
Integer. Either |
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:
-
Single field — use one column directly (e.g.
"gender","postcode"). -
Phonetic — Soundex or Double Metaphone encoding of a name field, so that near-spelling-variants of the same name block together.
-
Composite — concatenation of two or more fields into one blocking key (e.g. first letter of
lettername2+ birth year).
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 |
block1_vars |
Character vector of one or more column names to combine into
the primary blocking variable ( |
block2_vars |
Optional character vector for a second blocking variable
( |
block3_vars |
Optional character vector for a third blocking variable
( |
phonetic_vars |
Optional character vector of name columns to encode
phonetically. Each column |
phonetic_method |
One of |
birth_year_col |
Optional name of a |
postcode_col |
Optional name of a postcode column. If supplied, the first
3 digits are extracted as |
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:
block1Primary blocking key (always present).
block2Secondary blocking key (if
block2_varssupplied).block3Tertiary blocking key (if
block3_varssupplied).<col>_soundexor<col>_metaphonePhonetic encoding columns (if
phonetic_varssupplied).birth_yearInteger birth year (if
birth_year_colsupplied).postcode3First 3 digits of postcode (if
postcode_colsupplied).
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).
|
linkage_type |
The linkage to perform. As of starling 1.1.0 the preferred
value is Legacy codes: |
event_type |
Required when |
method |
Linkage engine. |
event_date |
The anchor date used to define the linkage window and determine valid vaccinations or related admissions.
This parameter is critical for determining valid vaccinations (must occur before |
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 |
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 |
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 |
perch_before_linking |
Logical. If |
inspect_matches |
Logical. If |
inspect_extra_vars |
Character vector of additional column names (present in both
|
resume_from_pairs |
A reviewed pairs table – normally the object returned by
|
vax_window |
A named list defining the vaccination validity window relative
to
Example: Overridden by |
cohort_window |
An optional named list defining a calendar-based
observation window that replaces
When |
days_allowed_before_event |
Numeric. For |
days_allowed_after_event |
Numeric. For |
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 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 (
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 |
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 |
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:
-
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. -
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). -
check_medicareto validate Medicare check digits and flag invalid numbers before they enter comparison scoring. -
flock()to create up to three blocking variables at different specificity levels (coarse, medium, fine) — pass one to theblocking_varargument below. -
murmurationwithlinkage_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. -
murmurationwithlinkage_type = "cohort2event", event_type = "hospitalisation"to link cases to hospital admissions. -
murmurationwithlinkage_type = "cohort2event", event_type = "vaccination"and a singleDateasevent_dateto link event linelists (flight manifests, outbreak investigations) to vaccination history as at that date. -
murmuration_plot, called directly on this function's own return value (passkeep_pairs_pred = TRUEto themurmurationcall above first — defaultFALSEskips building this table), to visualise the full linkage score distribution (jittered byblocking_var) and confirm the threshold before accepting the linked dataset. No need to re-derive the pairs table via reclin2 yourself. -
mudnester::preening()to prettify the dataframe prepping it for exploration, analysis and presentation. Great to use withgtsummary::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.
-
Letter-name fields swapped between
data_xanddata_y. If one dataset'smudnester::clean_the_nest()call mapslettername1to first name andlettername2to 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 twoclean_the_nest()calls are checked side by side, field mapping by field mapping. -
Too few
compare_varsfor thethreshold_valuein use. The maximum achievable Fellegi-Sunter weight rises with the number of comparison fields — a threshold calibrated against 5compare_vars(this function's default of16assumes 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. Lowerthreshold_valueand re-inspect withmurmuration_plotrather than concluding the linkage itself failed. -
Inconsistent cleaning/encoding between
data_xanddata_y. Two records that are obviously the same person to a human don't match if one side hasgender = "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 bothcompare_varsscoring (cause 2 above) andblocking_varalignment (cause 4 below) at once, since both are built from the same cleaned fields. -
blocking_vardoesn't mean the same thing on both sides. Blocking keys are literal string concatenations — a block built asgender + postcodeondata_xandgender + dob_yrondata_y(or the "same" block built by twoflock()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 = TRUEshows a near-zero candidate-pair count, not just a low-scoring one. Ablocking_varthat's too fine-grained on its own (e.g. exactdobwith 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. -
Vaccination data left in long (one-row-per-dose) format.
clean_the_nest(data_type = "vaccination")does not pivot tovax_date_1/vax_type_1, ... on its own —lie_nest_flat = TRUEis required. Without it, the data passes through unpivoted with no error fromclean_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 = TRUEwas passed to this call;NULLotherwise (the new default). The full candidate-pairs scoring table (every compared pair, not just the ones that clearedthreshold_value), with the realisedblocking_varvalue joined on for each pair.attr(x, "blocking_var")The
blocking_varvalue actually used.attr(x, "threshold_value")The
threshold_valueactually 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 |
threshold |
Numeric or |
blocking_var |
Character or |
max_levels |
Integer. If more blocking strata are present than this,
|
weight_col |
Name of the column containing linkage weights. Default
|
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 |
jitter_width |
Numeric. Horizontal jitter width within each blocking stratum's
column. Default |
point_alpha |
Numeric (0–1). Point transparency. Default |
point_size |
Numeric. Point size. Default |
show_subtitle |
Logical. Show the subtitle line (threshold, above/below
counts, and the sampling note when applicable)? Default |
show_counts |
Logical. Label each blocking stratum's column with its pair
count ( |
palette |
Character. Colour palette for match/non-match zones:
|
title |
Optional plot title string. |
interactive |
Logical. Return a plotly object ( |
pairs_pred |
|
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:
Every above-threshold pair is kept, in full, no matter how rare — unless there are more of them than
n_sampleitself, an unusual case in which they are themselves subsampled down ton_sample.The (usually much larger) below-threshold population is subsampled to fill whatever budget remains, proportionally within each blocking stratum so small strata aren't crowded out by large ones.
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
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 |
weight_col |
Character. Name of the numeric linkage weight column.
Default |
n_records_primary |
Integer or |
thresholds |
Numeric vector of candidate threshold values to evaluate.
Default |
clerical_window |
Numeric. Width of the clerical review zone centred on
each threshold value: the band
|
highlight_thresholds |
Numeric vector. Threshold values to mark with
|
report |
Logical. If |
plot |
Logical. If |
palette |
Character. Colour palette: |
interactive |
Logical. If |
Details
## Interpreting the output
Use perch() together with murmuration_plot:
-
murmuration_plot()confirms the weight distribution is bimodal and shows you where the valley between the two clusters lies. -
perch()quantifies the match count, link rate, and clerical burden at each candidate cutoff in that valley. 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, runmurmuration(inspect_matches = TRUE)instead, review the candidates (settingmatch_overridewhere a manual judgement should win), and finish withmurmuration(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:
thresholdNumeric. The candidate cutoff.
n_aboveInteger. Pairs with weight
\geqthreshold (accepted as matches at this cutoff).n_belowInteger. Pairs with weight
<threshold (rejected as non-matches).pct_aboveNumeric. Percentage of all pairs above threshold.
n_clericalInteger. Pairs in the clerical review zone [
threshold - clerical_window/2,threshold + clerical_window/2].pct_clericalNumeric. Percentage in the clerical zone.
link_rateNumeric or
NA. Proportion ofn_records_primaryrecords that would receive a match. Only populated whenn_records_primaryis supplied.referenceCharacter. Annotation for the four highlighted threshold values;
NAfor 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, |
data2 |
Second data frame (typically the vaccination/hospitalisation dataset,
|
linkage_vars |
Character vector of column names that will be used as
|
id_col1 |
Name of the unique record identifier in |
id_col2 |
Name of the unique record identifier in |
blocking_vars |
Character vector of planned blocking variable names to check
for completeness. If |
date_cols |
Character vector of date column names to check for plausibility
(no future dates, no dates before 1900). |
medicare_col |
Name of the Medicare number column if present and to be
validated. |
name_cols |
Character vector of name columns to check for short strings
(potential initials or truncations), all-numeric entries, and excessive
punctuation. Default checks |
min_name_length |
Integer. Names shorter than this are flagged as
potentially truncated or coded. Default |
verbose |
Logical. Print the full report to console? Default |
Value
Invisibly, a named list with the following elements:
completenessA data frame: variable, dataset, n_present, n_missing, pct_missing for each linkage variable.
duplicatesA data frame: dataset, n_records, n_unique_ids, n_duplicate_ids, pct_duplicate.
blocking_completenessCompleteness of blocking variables, or
NULLif not checked.date_checksDate plausibility results, or
NULLif not checked.medicareMedicare validity results from
check_medicare(), orNULLif not checked.name_checksName quality results, or
NULLif not checked.factor_consistencyComparison of factor levels for shared categorical columns.
overlap_summaryApproximate overlap statistics for key demographic variables.
flagsCharacter 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)