| murmuration | R Documentation |
**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.
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
)
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 |
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_medicare to 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 the blocking_var argument below.
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.
murmuration with linkage_type = "cohort2event", event_type = "hospitalisation" to link cases to hospital admissions.
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.
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.
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.
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.
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.
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.
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.
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.
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, ...).
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.
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. \Sexpr[results=rd]{tools:::Rd_expr_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. \Sexpr[results=rd]{tools:::Rd_expr_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.
# 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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.