library(starling)
library(mudnester) # clean_the_nest() and the clutch_* datasets
library(dplyr)
library(ggplot2)
aviary_cols <- c(satin = "#325D88", chestnut = "#86251C", wattle = "#D8A31A",
evergreen = "#08403B", mud = "#A67D4C", slate = "#3E3F3A")
This vignette demonstrates the complete starling
probabilistic record linkage workflow (Fellegi-Sunter scoring [3], run
through reclin2 [4]): pre-linkage audit, blocking,
threshold sensitivity analysis, linkage, post-linkage validation, and
the analysis the linkage exists to serve. The scenario mirrors a routine
SCPHU task and the design of a regional Queensland linkage study of
COVID-19 vaccine effectiveness [1]: link a notifiable-disease linelist
to the Australian Immunisation Register (AIR) to establish COVID-19
vaccination status at onset, link the same linelist to hospital
admissions to establish severity, and estimate vaccine effectiveness
(VE) against hospitalisation.
The data are three of the clutch teaching datasets
shipped in mudnester:
| Dataset | Rows | Role here |
|---|---|---|
clutch_cases |
3,182 | data_x: notified COVID-19, influenza, RSV and measles
cases |
clutch_air |
31,200 | data_y (vaccination): one row per vaccine
encounter |
clutch_hospital |
4,201 | data_y (hospitalisation): one row per episode of
care |
All three are synthetic – no real person data – with the identifier
errors real extracts carry (typos, nicknames, swapped day/month, missing
and household-shared Medicare numbers). Every record also carries a
truth_id, which real data never has. It is used here only
to grade the linkage.
mudnester::clean_the_nest() standardises every source
into the same schema. Roughly one notification in ten has no onset date,
so the specimen date stands in for it first – murmuration()
anchors every event window on event_date.
cases_raw <- clutch_cases |>
mutate(
onset_imputed = is.na(onset_date), # keep a flag
onset_date = coalesce(onset_date, specimen_date) # fall back to the specimen date
)
cases_clean <- clean_the_nest(
cases_raw,
data_type = "cases",
drop_eggs = TRUE,
id_var = "notification_id",
diagnosis = "condition",
lettername1 = "first_name",
lettername2 = "surname",
dob = "date_of_birth",
gender = "sex",
postcode = "postcode",
medicare = "medicare_number",
onset_date = "onset_date",
keep_vars = c("truth_id", "onset_imputed")
)
**(*)> One vaccine type at a time.** Filter the AIR extract to the vaccine you are studying before
clean_the_nest(lie_nest_flat = TRUE)andmurmuration(). Otherwisevax_date_1,vax_date_2, … interleave every vaccine the person has had – influenza, zoster, MMR – and the dose counts andvaccination_statusmean “any vaccine”, not “a COVID-19 dose”. One vaccine per call is also howmurmuration()is designed (?murmuration, “Linking one cohort to several event streams”).
air_covid_raw <- clutch_air |>
filter(antigen == "COVID-19") # the one vaccine this analysis is about
air_covid <- clean_the_nest(
air_covid_raw,
data_type = "vaccination",
lie_nest_flat = TRUE, # one row per person: vax_date_1, vax_type_1, ...
drop_eggs = TRUE,
id_var = "air_id",
lettername1 = "given_name",
lettername2 = "family_name",
dob = "date_of_birth",
gender = "sex",
postcode = "postcode",
medicare = "medicare_card",
medicare_irn = "medicare_irn", # the AIR stores the IRN in its own column
vax_type = "antigen",
vax_date = "date_of_service",
keep_vars = "truth_id"
)
cases_clean |>
count(diagnosis)
#> diagnosis n
#> 1 COVID-19 1400
#> 2 Influenza 1150
#> 3 Measles 12
#> 4 RSV 620
c(covid_doses = nrow(air_covid_raw), people_with_a_covid_dose = nrow(air_covid))
#> covid_doses people_with_a_covid_dose
#> 8131 4530
preflight()Before generating a single candidate pair, preflight()
checks completeness of the linkage variables, duplicate identifiers,
date plausibility, Medicare validity, name quality and factor-level
consistency across both datasets.
cases_covid_clean <- cases_clean |>
filter(diagnosis == "COVID-19")
audit <- preflight(
data1 = cases_covid_clean,
data2 = air_covid,
linkage_vars = c("lettername1", "lettername2", "dob", "medicare10"),
id_col1 = "id_var",
id_col2 = "id_var",
date_cols = c("dob", "onset_date"),
medicare_col = "medicare10",
verbose = FALSE
)
knitr::kable(audit$completeness, caption = "Completeness of the linkage variables")
| variable | dataset | n_records | n_present | n_missing | pct_missing |
|---|---|---|---|---|---|
| lettername1 | data1 | 1400 | 1395 | 5 | 0.4% |
| lettername2 | data1 | 1400 | 1400 | 0 | 0% |
| dob | data1 | 1400 | 1398 | 2 | 0.1% |
| medicare10 | data1 | 1400 | 1183 | 217 | 15.5% |
| lettername1 | data2 | 4530 | 4530 | 0 | 0% |
| lettername2 | data2 | 4530 | 4530 | 0 | 0% |
| dob | data2 | 4530 | 4530 | 0 | 0% |
| medicare10 | data2 | 4530 | 4489 | 41 | 0.9% |
audit$flags
#> [1] "[MEDICARE] 53 failed checksum in data1"
The row to notice is Medicare: it is missing on 16% of COVID-19 notifications but almost never on the AIR. That single fact shapes the score distribution in Step 4.
check_medicare()An invalid Medicare number that happens to resemble someone else’s
adds spurious weight to a false pair. Setting it to NA is
better: the EM algorithm treats NA as “not observed” and it
contributes nothing, positive or negative.
cases_checked <- cases_clean |>
check_medicare(medicare_col = "medicare10", output_col = "medicare_valid",
verbose = FALSE) |>
mutate(medicare10 = if_else(medicare_valid %in% 0L, NA_character_, medicare10))
air_checked <- air_covid |>
check_medicare(medicare_col = "medicare10", output_col = "medicare_valid",
verbose = FALSE) |>
mutate(medicare10 = if_else(medicare_valid %in% 0L, NA_character_, medicare10))
bind_rows(
cases_checked |> mutate(dataset = "clutch_cases"),
air_checked |> mutate(dataset = "clutch_air (COVID-19)")
) |>
group_by(dataset) |>
summarise(
valid = sum(medicare_valid %in% 1L),
fails_checksum = sum(medicare_valid %in% 0L),
missing = sum(is.na(medicare_valid))
) |>
knitr::kable(caption = "Medicare numbers after check_medicare(): invalid ones are set to NA")
| dataset | valid | fails_checksum | missing |
|---|---|---|---|
| clutch_air (COVID-19) | 4489 | 0 | 41 |
| clutch_cases | 2578 | 113 | 491 |
flock()murmuration() only compares pairs that share a blocking
key. Gender plus birth year keeps nearly every true pair together at a
fraction of the cost of gender alone (see
vignette("pre-linkage-quality") for the measured
trade-off).
cases_blocked <- flock(cases_checked,
block1_vars = c("gender", "birth_year"),
birth_year_col = "dob")
air_blocked <- flock(air_checked,
block1_vars = c("gender", "birth_year"),
birth_year_col = "dob")
cases_covid <- cases_blocked |>
filter(diagnosis == "COVID-19")
c(covid_cases = nrow(cases_covid),
air_people = nrow(air_blocked),
strata = length(intersect(cases_covid$block1, air_blocked$block1)))
#> covid_cases air_people strata
#> 1400 4530 196
The first run leaves threshold_value at the starling
default of 16 and keeps the full candidate-pairs table
(keep_pairs_pred = TRUE) so it can be inspected. The
vaccination window counts a COVID-19 dose as current if it was given
14–182 days before onset.
linked_16 <- murmuration(
data_x = cases_covid, # one row per COVID-19 case
data_y = air_blocked, # one row per AIR person, COVID-19 doses only
linkage_type = "cohort2event", # a cohort linked to an event stream...
event_type = "vaccination", # ...of vaccinations
event_date = "onset_date", # each case's own anchor date
id_var = "id_var", # the case identifier, kept on every row
blocking_var = "block1", # only pairs of the same gender and birth year
compare_vars = c("lettername1", "lettername2", "dob", "medicare10"),
# threshold_value not set: the default, 16
vax_window = list(days_before = 14, days_after = 0, lookback_days = 182),
keep_pairs_pred = TRUE # keep every scored pair for the plots
)
perch() sweeps candidate thresholds over the scored
pairs without re-fitting anything. With plot = FALSE it
returns its table invisibly:
pp_16 <- attr(linked_16, "pairs_pred") |>
as.data.frame()
# the most a pair can score when Medicare is missing on one side
max_weight_no_medicare <- pp_16 |>
filter(is.na(medicare10)) |>
pull(weights) |>
max()
sweep <- perch(pp_16,
n_records_primary = nrow(cases_covid),
thresholds = seq(4, 20, by = 1),
report = FALSE,
plot = FALSE)
knitr::kable(sweep[, c("threshold", "n_above", "n_clerical", "link_rate", "reference")],
caption = "Accepted pairs and clerical burden at each candidate threshold")
| threshold | n_above | n_clerical | link_rate | reference |
|---|---|---|---|---|
| 4 | 2131 | 21568 | 1.5221 | NA |
| 5 | 1667 | 6796 | 1.1907 | NA |
| 6 | 991 | 1925 | 0.7079 | NA |
| 7 | 803 | 1373 | 0.5736 | NA |
| 8 | 795 | 1055 | 0.5679 | NA |
| 9 | 783 | 389 | 0.5593 | NA |
| 10 | 758 | 203 | 0.5414 | AIHW/WADLU: lower bound of clerical review zone |
| 11 | 612 | 290 | 0.4371 | NA |
| 12 | 602 | 280 | 0.4300 | NA |
| 13 | 600 | 256 | 0.4286 | NA |
| 14 | 505 | 125 | 0.3607 | NA |
| 15 | 503 | 152 | 0.3593 | PHRN: lower bound for <0.5% false-match rate (full variable set) |
| 16 | 502 | 175 | 0.3586 | starling default (balanced: Medicare + 2 names + DOB) |
| 17 | 487 | 505 | 0.3479 | NA |
| 18 | 450 | 503 | 0.3214 | NA |
| 19 | 425 | 502 | 0.3036 | NA |
| 20 | 0 | 487 | 0.0000 | AIHW/WADLU: upper bound of clerical zone / confirmed matches above |
The count of accepted pairs barely moves between about 7 and 10, then
falls away in steps above 10. The first step is the Medicare effect: a
true pair whose Medicare number is missing on one side can score at most
the name and date-of-birth weights, which here sum to about 10.6. At 16
every one of those true pairs is thrown away, and so is every true pair
whose card was reissued between the two records (a different tenth
digit; see vignette("threshold-selection"), which measures
both).
murmuration_plot(linked_16, max_levels = 10)
The valley between the non-match cloud and the lower match cluster
sits near 8, so the linkage is re-run there – the same
look-before-fixing discipline an infant immunisation coverage study
applied to its birth-register matching [2]. The starling default and the
AIHW/WADLU and PHRN benchmarks in the perch() table all
assume a five-variable key with a Medicare number present and current on
both sides; with four variables and frequent Medicare gaps the scale is
simply lower.
| Range | Source | Meaning |
|---|---|---|
| 10–20 | AIHW / WA Data Linkage Unit | Clerical review zone |
| 15–20 | PHRN | Operational target for <0.5% false-match rate (full variable set) |
| 16 | starling default | Calibrated for 5 comparison variables with an agreeing Medicare number |
murmuration()linked_cov <- murmuration(
data_x = cases_covid, # one row per COVID-19 case
data_y = air_blocked, # one row per AIR person, COVID-19 doses only
linkage_type = "cohort2event",
event_type = "vaccination",
event_date = "onset_date", # the window is measured back from onset
id_var = "id_var",
blocking_var = "block1", # gender + birth year
compare_vars = c("lettername1", "lettername2", "dob", "medicare10"),
threshold_value = 8, # the valley seen in Step 4
vax_window = list(days_before = 14, # a dose counts from 14 days old...
days_after = 0,
lookback_days = 182), # ...until 182 days old
suffix = "_cov", # tag every column this call adds
keep_pairs_pred = TRUE
)
bind_rows(
linked_16 |> summarise(threshold = 16,
linked_to_air = sum(!is.na(id_var_y)),
current_dose = sum(vaccination_status == "Vaccinated")),
linked_cov |> summarise(threshold = 8,
linked_to_air = sum(!is.na(id_var_y_cov)),
current_dose = sum(vaccination_status_cov == "Vaccinated"))
) |>
knitr::kable(caption = "COVID-19 cases linked to an AIR record, and with a dose 14-182 days before onset")
| threshold | linked_to_air | current_dose |
|---|---|---|
| 16 | 502 | 119 |
| 8 | 777 | 194 |
suffix = "_cov" tags every column this call contributed
(weights_cov, id_var_y_cov,
vaccination_status_cov, vax_date_1_cov, …)
while the case columns, including id_var, stay plain – so
the result can be joined to the hospital linkage in Step 8 without
collisions. The vaccination route returns an ordinary, ungrouped data
frame with one row per case. Alongside the in-window
vax_date_*/vax_type_* columns it adds:
| Column | Meaning |
|---|---|
vaccination_status |
"Vaccinated" if any dose falls inside
vax_window, otherwise "Unvaccinated"
(including cases with no AIR record) |
vaccination_status_num |
The same as 1/0, ready for a model |
total_valid_vax |
Number of in-window doses |
first_vax_date, last_vax_date (and
_type) |
Earliest and latest in-window dose |
tsv |
Days from the last in-window dose to event_date; 0 when
unvaccinated |
“Vaccinated” below means
vaccination_status_cov == "Vaccinated".
linked_cov |>
count(vaccination_status_cov, total_valid_vax_cov, name = "cases") |>
knitr::kable(caption = "vaccination_status against the number of in-window doses (threshold 8)")
| vaccination_status_cov | total_valid_vax_cov | cases |
|---|---|---|
| Unvaccinated | 0 | 1206 |
| Vaccinated | 1 | 188 |
| Vaccinated | 2 | 6 |
murmuration_plot(linked_cov, max_levels = 10, palette = "sch")
If the distribution is cleanly bimodal and the above-threshold count
matches expectations, this is normally as far as you need to go. If
specific borderline pairs deserve a human judgement, see
vignette("clinical-linkage-review") for
inspect_matches and resume_from_pairs.
In production this step needs a clerical review sample. Here the
matched AIR record’s truth_id can be compared with the
case’s directly.
# the truth_id behind each matched AIR record -- used only to grade the links
air_truth <- air_blocked |>
select(id_var_y_cov = id_var, truth_id_air = truth_id)
grading <- linked_cov |>
left_join(air_truth, by = "id_var_y_cov") |>
summarise(
n_links = sum(!is.na(id_var_y_cov)),
n_correct = sum(truth_id == truth_id_air, na.rm = TRUE)
)
n_links <- grading$n_links
n_correct <- grading$n_correct
n_true <- cases_covid |>
filter(truth_id %in% air_blocked$truth_id) |>
nrow()
tibble(
measure = c("Accepted links", "Correct links", "Cases with a true AIR record",
"Precision (%)", "Recall (%)"),
value = c(n_links, n_correct, n_true,
round(100 * n_correct / n_links, 1),
round(100 * n_correct / n_true, 1))
) |>
knitr::kable()
| measure | value |
|---|---|
| Accepted links | 777.0 |
| Correct links | 769.0 |
| Cases with a true AIR record | 796.0 |
| Precision (%) | 99.0 |
| Recall (%) | 96.6 |
Common names and family members who share a Medicare card and a birth
year can put a second AIR record above the threshold.
murmuration() keeps the highest-weighted candidate for each
case (earlier releases kept the first in data_y row order),
so the precision recomputed from the candidate-pairs table matches the
linkage’s own. The highest weight is usually, but not always, the right
person:
# every candidate pair above the threshold, with both sides' truth_id
above <- attr(linked_cov, "pairs_pred") |>
as.data.frame() |>
filter(weights >= 8) |>
select(row_x = .x, row_y = .y, weights) |>
mutate(truth_x = cases_covid$truth_id[row_x],
truth_y = air_blocked$truth_id[row_y])
# cases with two or more candidates
multi_x <- above |>
count(row_x) |>
filter(n > 1) |>
pull(row_x)
# what murmuration() keeps: the highest-weighted candidate per case
best <- above |>
arrange(desc(weights)) |>
distinct(row_x, .keep_all = TRUE)
best_multi <- best |>
filter(row_x %in% multi_x)
tibble(
measure = c("Cases with 2+ candidates above 8",
" of which the highest-weighted candidate is the right person",
"Precision of murmuration()'s links (%)",
"Precision recomputed from the pairs, highest weight per case (%)"),
value = c(length(multi_x),
sum(best_multi$truth_x == best_multi$truth_y),
round(100 * n_correct / n_links, 1),
round(100 * mean(best$truth_x == best$truth_y), 1))
) |>
knitr::kable()
| measure | value |
|---|---|
| Cases with 2+ candidates above 8 | 18 |
| of which the highest-weighted candidate is the right person | 18 |
| Precision of murmuration()’s links (%) | 99 |
| Precision recomputed from the pairs, highest weight per case (%) | 99 |
Where the highest weight is the wrong person, the cause is a near-tie
between two plausible people, not the threshold: a higher
threshold_value drops most of the second candidates only by
also discarding true pairs that score in the same range. Reviewing those
cases (see vignette("clinical-linkage-review")) resolves
them without that cost, and where both records carry the IRN it settles
a family-member pair outright (see
vignette("pre-linkage-quality")).
The hospital extract codes sex as
"Male"/"Female", so it is recoded before
cleaning (otherwise no pair would ever share a block). Only acute
episodes are relevant; maternity and newborn episodes are left out. An
admission counts as disease-related if it starts between 7 days before
and 14 days after onset, and a death within 30 days of onset counts as a
COVID-19 death.
hosp_raw <- clutch_hospital |>
filter(care_type == "Acute") |> # no maternity or newborn episodes
mutate(sex = case_when(sex == "Male" ~ "M", # the hospital codes sex in full;
sex == "Female" ~ "F")) # every other source uses M/F
hosp_clean <- clean_the_nest(
hosp_raw,
data_type = "hospital",
drop_eggs = TRUE,
id_var = "ur_number",
event_id_var = "episode_id",
lettername1 = "given_name",
lettername2 = "family_name",
dob = "birth_date",
gender = "sex",
postcode = "postcode",
medicare = "medicare_no",
admission_date = "admit_date",
discharge_date = "separation_date",
hospital = "facility",
icd_code = "principal_diagnosis",
drg = "drg",
icu_date = "icu_date",
icu_hours = "icu_hours",
dod = "death_date", # age at admission is derived from dob and admit_date
keep_vars = c("truth_id", "diagnosis_codes")
)
hosp_blocked <- hosp_clean |>
check_medicare(medicare_col = "medicare10", output_col = "medicare_valid",
verbose = FALSE) |>
mutate(medicare10 = if_else(medicare_valid %in% 0L, NA_character_, medicare10)) |>
flock(block1_vars = c("gender", "birth_year"),
birth_year_col = "dob")
linked_hosp <- murmuration(
data_x = cases_blocked, # every case, all four conditions
data_y = hosp_blocked, # acute episodes
linkage_type = "cohort2event",
event_type = "hospitalisation",
event_date = "onset_date",
id_var = "id_var",
blocking_var = "block1", # gender + birth year
compare_vars = c("lettername1", "lettername2", "dob", "medicare10"),
threshold_value = 8,
days_allowed_before_event = 7, # admitted up to 7 days before onset...
days_allowed_after_event = 14, # ...or up to 14 days after
days_between_onset_death = 30, # a death within 30 days of onset
suffix = "_hosp",
keep_pairs_pred = TRUE
)
linked_hosp |>
summarise(cases = n(),
linked_to_hospital = sum(!is.na(id_var_y_hosp)),
admitted_in_window = sum(admission_outcome_hosp == "Admission")) |>
knitr::kable(caption = "Cases linked to an acute hospital record, and admitted in the window")
| cases | linked_to_hospital | admitted_in_window |
|---|---|---|
| 3182 | 319 | 319 |
murmuration_plot(linked_hosp, max_levels = 10)
The hospitalisation route adds admission_outcome,
first_admission_date, icu_outcome and
death_outcome (here suffixed _hosp). Columns
that come only from the hospital extract
(diagnosis_codes_hosp here) are blank for a case whose
matched admission falls outside the window, so they always describe the
in-window admission. The truth column repeats the same window rule using
truth_id, so the two can be compared.
# the truth: an acute admission of the same person within the same window
truth_adm <- cases_blocked |>
select(id_var, truth_id, onset_date) |>
inner_join(hosp_clean |> select(truth_id, admission_date),
by = "truth_id", relationship = "many-to-many") |>
filter(admission_date >= onset_date - 7,
admission_date <= onset_date + 14)
linked_hosp <- linked_hosp |>
mutate(admitted = admission_outcome_hosp == "Admission",
icu = icu_outcome_hosp == "ICU Admission",
died = death_outcome_hosp == "Died",
admitted_truth = id_var %in% truth_adm$id_var)
severity <- linked_hosp |>
group_by(condition = diagnosis) |>
summarise(cases = n(),
admitted = sum(admitted),
admitted_truth = sum(admitted_truth),
icu = sum(icu, na.rm = TRUE),
died_30d = sum(died, na.rm = TRUE)) |>
mutate(chr_pct = round(100 * admitted / cases, 1),
chr_truth_pct = round(100 * admitted_truth / cases, 1),
cfr_pct = round(100 * died_30d / cases, 2))
knitr::kable(severity, caption = "Case-hospitalisation (CHR) and case-fatality (CFR) by condition, linked vs truth")
| condition | cases | admitted | admitted_truth | icu | died_30d | chr_pct | chr_truth_pct | cfr_pct |
|---|---|---|---|---|---|---|---|---|
| COVID-19 | 1400 | 123 | 125 | 19 | 18 | 8.8 | 8.9 | 1.29 |
| Influenza | 1150 | 87 | 92 | 6 | 8 | 7.6 | 8.0 | 0.70 |
| Measles | 12 | 5 | 5 | 0 | 0 | 41.7 | 41.7 | 0.00 |
| RSV | 620 | 104 | 108 | 20 | 9 | 16.8 | 17.4 | 1.45 |
chr_long <- bind_rows(
severity |> transmute(condition, source = "Linked (threshold 8)", chr = chr_pct),
severity |> transmute(condition, source = "Truth", chr = chr_truth_pct)
)
ggplot(chr_long, aes(x = condition, y = chr, fill = source)) +
geom_col(position = position_dodge(width = 0.75), width = 0.7) +
scale_fill_manual(values = c("Linked (threshold 8)" = aviary_cols[["satin"]],
"Truth" = aviary_cols[["wattle"]])) +
labs(x = NULL, y = "Case-hospitalisation ratio (%)", fill = NULL) +
theme_minimal(base_size = 12) +
theme(legend.position = "bottom")
n_died_after_discharge <- linked_hosp |>
filter(died, dod_hosp > first_discharge_date_hosp) |>
nrow()
pct_covid_coded <- linked_hosp |>
filter(admitted, diagnosis == "COVID-19") |>
summarise(pct = round(100 * mean(grepl("U07[.]1|B97[.]2", diagnosis_codes_hosp)))) |>
pull(pct)
Two details worth knowing:
death_outcome measures from onset, not from separation, so
they are still counted.diagnosis_codes before
linking if your definition needs it.Both linkages hang off the same id_var, so they join
directly. Among COVID-19 cases, VE against hospitalisation is estimated
as one minus the risk ratio of admission, vaccinated versus not, from a
log-link Poisson model with robust (sandwich) standard errors – the
modified Poisson approach [5], which estimates the same risk ratio as
the log-binomial model of the published study [1] but always
converges.
covid <- linked_hosp |>
filter(diagnosis == "COVID-19") |>
select(id_var, truth_id, age, onset_date, admitted, admitted_truth) |>
inner_join(linked_cov |> select(id_var, vaccination_status_cov), by = "id_var") |>
mutate(vaccinated = vaccination_status_cov == "Vaccinated",
hospitalised = as.integer(admitted),
age_group = cut(age, c(-Inf, 50, 65, 80, Inf), right = FALSE,
labels = c("<50", "50-64", "65-79", "80+")))
# The same exposure from the truth: a COVID-19 dose 14-182 days before onset
vaccinated_truth_ids <- covid |>
select(id_var, truth_id, onset_date) |>
inner_join(clutch_air |>
filter(antigen == "COVID-19") |>
select(truth_id, date_of_service),
by = "truth_id", relationship = "many-to-many") |>
mutate(days_since_dose = as.numeric(onset_date - date_of_service)) |>
filter(days_since_dose >= 14, days_since_dose <= 182) |>
pull(id_var)
covid <- covid |>
mutate(vaccinated_truth = id_var %in% vaccinated_truth_ids,
hospitalised_truth = as.integer(admitted_truth))
covid |>
mutate(vaccination = if_else(vaccinated, "Vaccinated", "Unvaccinated"),
admission = if_else(hospitalised == 1, "admitted", "not admitted")) |>
count(age_group, vaccination, admission, name = "cases") |>
knitr::kable(caption = "COVID-19 cases by age group, vaccination status and admission (linked data)")
| age_group | vaccination | admission | cases |
|---|---|---|---|
| <50 | Unvaccinated | admitted | 9 |
| <50 | Unvaccinated | not admitted | 449 |
| <50 | Vaccinated | not admitted | 7 |
| 50-64 | Unvaccinated | admitted | 11 |
| 50-64 | Unvaccinated | not admitted | 218 |
| 50-64 | Vaccinated | not admitted | 26 |
| 65-79 | Unvaccinated | admitted | 46 |
| 65-79 | Unvaccinated | not admitted | 286 |
| 65-79 | Vaccinated | admitted | 6 |
| 65-79 | Vaccinated | not admitted | 80 |
| 80+ | Unvaccinated | admitted | 43 |
| 80+ | Unvaccinated | not admitted | 142 |
| 80+ | Vaccinated | admitted | 8 |
| 80+ | Vaccinated | not admitted | 67 |
| NA | Unvaccinated | not admitted | 2 |
Vaccinated cases are concentrated in the oldest age groups, where admission is most common, so the crude comparison understates protection. Age adjustment matters here:
ve_fits <- list(
"Crude (linked)" = glm(hospitalised ~ vaccinated,
family = poisson(link = "log"), data = covid),
"Age-adjusted (linked)" = glm(hospitalised ~ vaccinated + age_group,
family = poisson(link = "log"), data = covid),
"Age-adjusted (truth)" = glm(hospitalised_truth ~ vaccinated_truth + age_group,
family = poisson(link = "log"), data = covid)
)
ve_rows <- list()
for (model_name in names(ve_fits)) {
fit <- ve_fits[[model_name]]
X <- model.matrix(fit)
bread <- summary(fit)$cov.unscaled
meat <- crossprod(X * (fit$y - fitted(fit)))
se <- sqrt(diag(bread %*% meat %*% bread))[2] # robust SE, vaccination term
b <- coef(fit)[2]
ve_rows[[model_name]] <- tibble(
model = model_name,
VE = round(100 * (1 - exp(b)), 1),
lower = round(100 * (1 - exp(b + 1.96 * se)), 1),
upper = round(100 * (1 - exp(b - 1.96 * se)), 1)
)
}
ve_table <- bind_rows(ve_rows)
knitr::kable(ve_table, caption = "VE (%) against hospitalisation among COVID-19 cases, 95% CI (robust)")
| model | VE | lower | upper |
|---|---|---|---|
| Crude (linked) | 20.2 | -36.4 | 53.3 |
| Age-adjusted (linked) | 54.6 | 22.8 | 73.3 |
| Age-adjusted (truth) | 56.7 | 26.4 | 74.5 |
ve_table |>
mutate(model = factor(model, levels = rev(model))) |>
ggplot(aes(x = VE, y = model)) +
geom_vline(xintercept = 0, colour = aviary_cols[["slate"]], linetype = "dashed") +
geom_errorbar(aes(xmin = lower, xmax = upper), width = 0.2, orientation = "y",
colour = aviary_cols[["satin"]]) +
geom_point(size = 3, colour = aviary_cols[["chestnut"]]) +
labs(x = "Vaccine effectiveness against hospitalisation (%)", y = NULL) +
theme_minimal(base_size = 12)
The age-adjusted estimate from the linked data (54.6%, 95% CI 22.8 to 73.3) sits close to the estimate from perfect linkage (56.7%), so linkage error at this threshold barely moves the answer. For comparison, the published regional Queensland study reported 69.9% (44.3–83.8) for a primary course and 81.8% (39.5–94.5) with a booster, adjusting for age (<50/≥50), sex and Indigenous status [1]. The synthetic world was generated with a weaker effect; the point here is the workflow, not the number.
library(starling)
library(mudnester)
library(dplyr)
# 0. Clean every source the same way -- and the AIR for ONE vaccine type only
cases <- clutch_cases |>
mutate(onset_date = coalesce(onset_date, specimen_date)) |>
clean_the_nest(data_type = "cases", id_var = "notification_id", ...)
air <- clutch_air |>
filter(antigen == "COVID-19") |>
clean_the_nest(data_type = "vaccination", lie_nest_flat = TRUE,
medicare = "medicare_card", medicare_irn = "medicare_irn", ...)
hosp <- clutch_hospital |>
mutate(sex = case_when(sex == "Male" ~ "M", sex == "Female" ~ "F")) |>
clean_the_nest(data_type = "hospital", ...)
# 1-3. Audit, Medicare validation (invalid -> NA), blocking
preflight(cases, air, linkage_vars = c("lettername1", "lettername2", "dob", "medicare10"))
cases <- cases |>
check_medicare() |>
mutate(medicare10 = if_else(medicare_valid %in% 0L, NA_character_, medicare10)) |>
flock(block1_vars = c("gender", "birth_year"), birth_year_col = "dob")
# 4. Look before trusting a threshold (threshold_value defaults to 16)
first_pass <- murmuration(data_x = cases, data_y = air,
linkage_type = "cohort2event", event_type = "vaccination",
event_date = "onset_date", id_var = "id_var", blocking_var = "block1",
compare_vars = c("lettername1", "lettername2", "dob", "medicare10"),
keep_pairs_pred = TRUE)
perch(attr(first_pass, "pairs_pred"), n_records_primary = nrow(cases))
murmuration_plot(first_pass)
# 5-7. Link at the chosen threshold, one call per event stream, then validate
vax <- murmuration(data_x = cases, data_y = air, ..., threshold_value = 8,
suffix = "_cov",
vax_window = list(days_before = 14, days_after = 0, lookback_days = 182))
adm <- murmuration(data_x = cases, data_y = hosp, linkage_type = "cohort2event",
event_type = "hospitalisation", ..., threshold_value = 8, suffix = "_hosp")
# 8-10. Join on id_var and analyse
cohort <- adm |>
inner_join(vax |> select(id_var, vaccination_status_cov), by = "id_var")
sessionInfo()
#> R version 4.5.2 (2025-10-31 ucrt)
#> Platform: x86_64-w64-mingw32/x64
#> Running under: Windows 11 x64 (build 26100)
#>
#> Matrix products: default
#> LAPACK version 3.12.1
#>
#> locale:
#> [1] LC_COLLATE=C LC_CTYPE=English_Australia.utf8
#> [3] LC_MONETARY=English_Australia.utf8 LC_NUMERIC=C
#> [5] LC_TIME=English_Australia.utf8
#>
#> time zone: Australia/Brisbane
#> tzcode source: internal
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> other attached packages:
#> [1] ggplot2_4.0.3 dplyr_1.2.1 mudnester_0.9.0 starling_2.0.0
#>
#> loaded via a namespace (and not attached):
#> [1] sass_0.4.10 generics_0.1.4 tidyr_1.3.2
#> [4] lpSolve_5.6.23 stringi_1.8.7 digest_0.6.39
#> [7] magrittr_2.0.4 evaluate_1.0.5 grid_4.5.2
#> [10] timechange_0.4.0 RColorBrewer_1.1-3 fastmap_1.2.0
#> [13] jsonlite_2.0.0 purrr_1.2.1 scales_1.4.0
#> [16] stringdist_0.9.17 jquerylib_0.1.4 cli_3.6.5
#> [19] rlang_1.3.0 withr_3.0.2 cachem_1.1.0
#> [22] yaml_2.3.12 otel_0.2.0 tools_4.5.2
#> [25] parallel_4.5.2 vctrs_0.7.1 R6_2.6.1
#> [28] lifecycle_1.0.5 lubridate_1.9.5 snakecase_0.11.1
#> [31] stringr_1.6.0 janitor_2.2.1 pkgconfig_2.0.3
#> [34] pillar_1.11.1 bslib_0.10.0 gtable_0.3.6
#> [37] data.table_1.18.2.1 glue_1.8.0 Rcpp_1.1.1
#> [40] xfun_0.56 tibble_3.3.1 tidyselect_1.2.1
#> [43] rstudioapi_0.18.0 knitr_1.51 farver_2.1.2
#> [46] htmltools_0.5.9 labeling_0.4.3 rmarkdown_2.31
#> [49] phonics_1.3.10 compiler_4.5.2 S7_0.2.1
#> [52] reclin2_0.6.0