12  A worked record-linkage pipeline

This chapter links two files of people end to end: a service enrolment extract and a claims extract from a different system, holding many of the same people. Nothing is pre-cleaned. Every step is one of the functions in this package, and because the data carry a hidden person_id, every claim made along the way is measured rather than asserted.

The shape of the problem is always the same:

Step Question Section
1 What is actually in these columns? sec-wf-profile
2 Do the two files agree on types and spelling? sec-wf-standardise
3 Which records are even worth comparing? sec-wf-block
4 How alike is each candidate pair, field by field? sec-wf-score
5 Which pairs do we accept, and which go to a human? sec-wf-decide
6 What is one person’s identifier across both files? sec-wf-entities
7 How well did it work, and what did it cost? sec-wf-evaluate

12.1 The two files

files  <- people_files(n_enrol = 50000, overlap = 0.6)
enrol  <- files$enrol
claims <- files$claims
c(enrol = nrow(enrol), claims = nrow(claims))
 enrol claims 
 50000  37500 

The enrolment file is the tidy one: name in three fields, date of birth as a Date, sex as a one-letter code, address in parts, postcode as zero-padded text.

enrol[1:4, c("enrol_id", "given_name", "middle_name", "surname", "dob", "sex")]
  enrol_id given_name middle_name  surname        dob sex
1  E000001       LELL        <NA> CAMPBELL 1974-07-28   F
2  E000002    BARBARA         KES    ZELOR 1962-08-20   F
3  E000003      PETER      DANIEL    JONES 1962-09-12   U
4  E000004     NATHAN        <NA>   ROGRAS 1974-10-05   M
enrol[1:4, c("unit", "number", "street", "street_type", "suburb", "postcode")]
  unit number street street_type     suburb postcode
1   11    239   MAIN       DRIVE CAMBERWELL     0818
2   20    441   KING    CRESCENT CAMBERWELL     3143
3 <NA>     76  LOGAN      PARADE    PRAHRAN     0817
4 <NA>    337  BEACH      AVENUE    PRAHRAN     0878

The claims file is what a linkage project is usually handed:

claims[1:6, ]
  claim_id           patient_name date_of_birth  gender
1  C005152       Gevese,  Mr John    28/08/2012    Male
2  C036231       Sheni, Fena Ryan    01/05/1979 Unknown
3  C029263   Campbell,  Mr Pell      02/11/2019    Male
4  C002516     Gofy, Andrew Keski    04/11/1942    Male
5  C021237         Fises, Dr Loll    14/06/2009  Female
6  C022990 Molxson, Robert Nenall    05/10/1969    Male
                        address_line postcode
1          278 Park Ave, Carlton VIC     3087
2         402 Hill Ln, Glen Iris VIC     3013
3  271 Stanley Parade, Footscray VIC     3177
4          135 Park Pde, Fitzroy VIC     3145
5     35 Sandgate Court, Carlton VIC      851
6 33 Station Tce, Mount Waverley VIC     3015

One name field holding "SURNAME, Title Given Middle" in title case, with doubled and trailing spaces. The date of birth as "DD/MM/YYYY" text. Sex spelled out, sometimes "Unknown", sometimes blank. The address as one free-text line with a unit prefix and an abbreviated street type. And a numeric postcode, so every Northern Territory postcode has lost its leading zero.

12.2 Step 1: profile before you match

The fastest way to be wrong about a column is to assume you know its shape. string_shape() collapses each value to a character-class pattern, so the distinct formats in a column are a table() away:

head(sort(table(string_shape(claims$date_of_birth)), decreasing = TRUE), 3)
99/99/9999 
     37500 
head(sort(table(string_shape(claims$patient_name)), decreasing = TRUE), 5)

  Aaaaaa, Aaaa   Aaaaa, Aaaaa  Aaaaaa, Aaaaa    Aaaaa, Aaaa Aaaaaa, Aaaaaa 
           351            344            332            293            263 

Every date of birth is 99/99/9999, so one fixed format will parse the column. The name column has many shapes, which is the signal that it needs parsing rather than comparing as it stands.

Two more questions worth asking of every incoming column — how much is missing, and how much is a placeholder:

c(gender_blank   = mean(!nzchar(claims$gender)),
  gender_unknown = mean(claims$gender == "Unknown"),
  name_untrimmed = mean(claims$patient_name != trimws(claims$patient_name)),
  dob_jan_1      = mean(fgrepl("^01/01/", claims$date_of_birth)),
  postcode_short = mean(fnchar(as.character(claims$postcode)) < 4))
  gender_blank gender_unknown name_untrimmed      dob_jan_1 postcode_short 
    0.06288000     0.06189333     0.25005333     0.02240000     0.32978667 

About one date of birth in forty-five is 1 January — far more than the 1-in-365 a real population gives. That is the placeholder a clerk types when the date is unknown, and a blocking pass on the exact date would build one huge useless block out of it. sec-wf-block caps it, and a real project would set those dates to NA instead.

12.3 Step 2: standardise, field by field

The goal is one data frame per file with the same column names, the same types and the same spelling conventions. Every line below is vectorised over the whole column.

The name field

fupper() and fsquish() first, so nothing downstream has to think about case or whitespace again; then fsplit_field() on the comma; then freplace_tokens() to drop the titles. freplace_tokens() matches whole tokens from a dictionary in one pass, so "DR" goes and "DRUMMOND" stays — which a gsub("DR", "", ...) would not manage.

titles <- c("MR", "MRS", "MS", "MISS", "DR", "PROF", "REV", "SIR")

name  <- fsquish(fupper(claims$patient_name))
surn  <- ftrimws(fsplit_field(name, ",", 1))
rest  <- fsquish(freplace_tokens(ftrimws(fsplit_field(name, ",", 2)),
                                 titles, rep("", length(titles))))
given  <- fsplit_field(rest, " ", 1)
middle <- fsplit_field(rest, " ", 2)

data.frame(claims$patient_name, surn, given, middle)[1:6, ]
     claims.patient_name     surn  given middle
1       Gevese,  Mr John   GEVESE   JOHN   <NA>
2       Sheni, Fena Ryan    SHENI   FENA   RYAN
3   Campbell,  Mr Pell   CAMPBELL   PELL   <NA>
4     Gofy, Andrew Keski     GOFY ANDREW  KESKI
5         Fises, Dr Loll    FISES   LOLL   <NA>
6 Molxson, Robert Nenall  MOLXSON ROBERT NENALL

Apostrophes and hyphens are the other recurring name problem: the same person is O'BRIEN in one file and OBRIEN in the other, SMITH-JONES here and SMITH JONES there. Rather than choose, keep the name as given and compare on a form that ignores the difference. Three functions do different parts of that job:

variants <- c("O'BRIEN", "OBRIEN", "O BRIEN", "o'brien", "D'ARCY", "DARCY",
              "MULLER", "MÜLLER", "SMITH-JONES", "SMITH JONES")
data.frame(variants,
           ascii_fold  = ascii_fold(variants),
           fingerprint = fingerprint(variants),
           letters     = fgsub("[^A-Z]", "", fupper(variants)))
      variants  ascii_fold fingerprint    letters
1      O'BRIEN     O'BRIEN      obrien     OBRIEN
2       OBRIEN      OBRIEN      obrien     OBRIEN
3      O BRIEN     O BRIEN     brien o     OBRIEN
4      o'brien     o'brien      obrien     OBRIEN
5       D'ARCY      D'ARCY       darcy      DARCY
6        DARCY       DARCY       darcy      DARCY
7       MULLER      MULLER      muller     MULLER
8       MÜLLER      MULLER      muller      MLLER
9  SMITH-JONES SMITH-JONES  smithjones SMITHJONES
10 SMITH JONES SMITH JONES jones smith SMITHJONES

ascii_fold() is the one that matters for MÜLLER: it folds accented Latin letters to ASCII, so a file that lost its accents still matches one that kept them. fingerprint() (OpenRefine’s clustering key) lower-cases, folds, strips punctuation and sorts the words, which is what makes SMITH-JONES and SMITH JONES meet — but note that it keeps O BRIEN apart from OBRIEN, because there the space creates a second word rather than joining two. Stripping to letters alone collapses all four of the O'BRIEN spellings, at the cost of also collapsing names that differ only in their spacing. A blocking key wants the aggressive form; a score wants the gentle one, which is why jaro_winkler_tokens() exists — it folds punctuation and spacing inside the comparison, so the raw names can be compared as they were recorded:

jaro_winkler_tokens(c("O'BRIEN", "SMITH-JONES", "O'BRIEN"),
                    c("O BRIEN", "SMITH JONES", "OBRIEN"))
[1] 1 1 1
jaro_winkler(c("O'BRIEN", "SMITH-JONES", "O'BRIEN"),
             c("O BRIEN", "SMITH JONES", "OBRIEN"))
[1] 0.9142857 0.9636364 0.9571429

The date of birth

fas.Date() parses one fixed layout with no locale, no strptime() and no format guessing, and validates the calendar, so an impossible date becomes NA instead of silently rolling over:

dob <- fas.Date(claims$date_of_birth, format = "dmy")
c(parsed = sum(!is.na(dob)), failed = sum(is.na(dob)))
parsed failed 
 37500      0 
# Strictness is the point: base R's as.Date() guesses, fas.Date() refuses.
fas.Date(c("29/02/2024", "29/02/2023", "31/04/2024", "1/3/2024", NA),
         format = "dmy")
[1] "2024-02-29" NA           NA           NA           NA          

2024 is a leap year and 2023 is not; 31 April does not exist; and "1/3/2024" is not "DD/MM/YYYY" — a fixed-width format means fixed-width. Any of those being NA is a finding about the data, which is what you want at this stage, rather than a wrong date to discover later.

date_parts() splits a Date into year, month and day columns in one pass, which is how the cheap partial blocking keys get built:

parts <- date_parts(dob)
head(parts, 3)
  year month day
1 2012     8  28
2 1979     5   1
3 2019    11   2
head(format_date(dob, "y-m"), 3)      # "YYYY-MM", a coarser key
[1] "2012-08" "1979-05" "2019-11"

Sex, gender and the vocabulary problem

The two files use different vocabularies for the same field. Map both onto one, and keep “not recorded” distinct from “disagrees” — treating an unknown as a disagreement throws away true matches:

sex_code <- function(x) {
    x <- fupper(ftrimws(as.character(x)))
    out <- rep("U", length(x))
    out[x %in% c("M", "MALE", "1")]   <- "M"
    out[x %in% c("F", "FEMALE", "2")] <- "F"
    out
}
table(raw = claims$gender, coded = sex_code(claims$gender))
         coded
raw           F     M     U
              0     0  2358
  Female  16477     0     0
  Male        0 16344     0
  Unknown     0     0  2321

The comparison that goes with it returns agreement, disagreement, or neither:

sex_agree <- function(a, b) ifelse(a == "U" | b == "U", 0.5,
                                   as.numeric(a == b))
sex_agree(c("M", "M", "F", "U"), c("M", "F", "F", "F"))
[1] 1.0 0.0 1.0 0.5

The address

An address line is a street number, a street name, a street type and a locality, run together with the type abbreviated. Pull the unit off the front with fgsub(), split on the comma, and expand the abbreviations with a whole-token dictionary — the same freplace_tokens() trick as the titles, and the reason "ST KILDA" does not become "STREET KILDA":

street_abbrev <- c("ST", "RD", "AVE", "CT", "PL", "TCE", "PDE", "CRES",
                   "DR", "LN", "HWY", "BLVD")
street_full   <- c("STREET", "ROAD", "AVENUE", "COURT", "PLACE", "TERRACE",
                   "PARADE", "CRESCENT", "DRIVE", "LANE", "HIGHWAY",
                   "BOULEVARD")

raw_addr <- fupper(claims$address_line)
unit     <- fextract("[0-9]+", fextract("^U[0-9]+/", raw_addr))
body     <- fgsub("^U[0-9]+/", "", raw_addr)
street   <- fsquish(freplace_tokens(ftrimws(fsplit_field(body, ",", 1)),
                                    street_abbrev, street_full))
locality <- ftrimws(fgsub(" VIC$", "", fsplit_field(body, ",", 2)))

# Rows with a unit number, so the prefix is visible.
head(data.frame(claims$address_line, unit, street, locality)[!is.na(unit), ], 5)
                 claims.address_line unit               street  locality
9  U20/41 Stanley Pde, Glen Iris VIC   20    41 STANLEY PARADE GLEN IRIS
17 U17/66 Elizabeth Tce, Carlton VIC   17 66 ELIZABETH TERRACE   CARLTON
19   U1/124 Flinders Ln, Fitzroy VIC    1    124 FLINDERS LANE   FITZROY
24     U10/138 King Ave, Carlton VIC   10      138 KING AVENUE   CARLTON
26    U30/122 Hill Cres, Carlton VIC   30    122 HILL CRESCENT   CARLTON

fextract() returns the first match of a pattern per element, so the unit number comes out without a regmatches()/regexpr() pair. Note that "ST KILDA" survived the dictionary while "Flinders Cres" became "FLINDERS CRESCENT".

The postcode

A numeric postcode has lost its leading zeros. Pad it back, and validate rather than assume:

postcode <- fpad(as.character(claims$postcode), 4, pad = "0")
table(width = fnchar(postcode))
width
    4 
37500 
head(sort(table(string_shape(postcode)), decreasing = TRUE), 2)
 9999 
37500 

The standardised files

claims_std <- data.frame(
    claim_id       = claims$claim_id,
    given_name     = given,
    middle_name    = middle,
    surname        = surn,
    surname_key    = fingerprint(surn),
    dob            = dob,
    sex            = sex_code(claims$gender),
    unit           = unit,
    street_address = street,
    suburb         = locality,
    postcode       = postcode,
    stringsAsFactors = FALSE
)

enrol_std <- data.frame(
    enrol_id       = enrol$enrol_id,
    given_name     = enrol$given_name,
    middle_name    = enrol$middle_name,
    surname        = enrol$surname,
    surname_key    = fingerprint(enrol$surname),
    dob            = enrol$dob,
    sex            = sex_code(enrol$sex),
    unit           = enrol$unit,
    street_address = fsquish(paste(enrol$number, enrol$street,
                                    enrol$street_type)),
    suburb         = enrol$suburb,
    postcode       = enrol$postcode,
    stringsAsFactors = FALSE
)
str(claims_std, vec.len = 2)
'data.frame':   37500 obs. of  11 variables:
 $ claim_id      : chr  "C005152" "C036231" ...
 $ given_name    : chr  "JOHN" "FENA" ...
 $ middle_name   : chr  NA "RYAN" ...
 $ surname       : chr  "GEVESE" "SHENI" ...
 $ surname_key   : chr  "gevese" "sheni" ...
 $ dob           : Date, format: "2012-08-28" "1979-05-01" ...
 $ sex           : chr  "M" "U" ...
 $ unit          : chr  NA NA ...
 $ street_address: chr  "278 PARK AVENUE" "402 HILL LANE" ...
 $ suburb        : chr  "CARLTON" "GLEN IRIS" ...
 $ postcode      : chr  "3087" "3013" ...

12.4 Step 3: block, and know what each pass buys you

Comparing every enrolment record with every claim is 1,500,000,000 pairs. Blocking compares only the records that agree on some key. One key misses every true match with an error in that key, so a linkage runs several passes with keys that fail in different ways:

Pass Key Survives
1 surname code + exact date of birth any error in the given name or address
2 surname code + year of birth a transposed or shifted date of birth
3 given-name code + exact date of birth a changed or misspelled surname
4 surname code + first initial + postcode a date of birth that is wholly wrong

rLink() takes those four passes as four list()s, and the blocking keys are written as expressions, so the phonetic code and the date part are computed inside the call:

cand <- rLink(
    enrol_std, claims_std,
    block = list(
        surname_dob   = list(soundex(surname), dob),
        surname_year  = list(soundex(surname), format_date(dob, "y")),
        given_dob     = list(soundex(given_name), dob),
        name_postcode = list(soundex(surname), fsubstr(given_name, 1, 1),
                             postcode)
    ),
    # The 1 January placeholder, and the commonest surname codes, would
    # otherwise build blocks that cost more than they can return.
    max_block_size = 2000,
    keep = character()
)
nrow(cand)
[1] 168462
table(pass = cand$pass)
pass
     1      2      3      4 
 24907 136244   3620   3691 

Because the data carry a truth, each pass can be charged for what it brought in:

truth <- same_person(files, cand$index_1, cand$index_2)
marginal <- t(sapply(sort(unique(cand$pass)), function(p) c(
    candidates = sum(cand$pass == p),
    true_pairs = sum(truth & cand$pass == p),
    yield      = round(mean(truth[cand$pass == p]), 3))))
rownames(marginal) <- paste("pass", sort(unique(cand$pass)))
marginal
       candidates true_pairs yield
pass 1      24907      24533 0.985
pass 2     136244       1441 0.011
pass 3       3620       2861 0.790
pass 4       3691       1165 0.316
c(true_pairs      = true_pair_count(files),
  found           = sum(truth),
  blocking_recall = round(sum(truth) / true_pair_count(files), 4),
  reduction_ratio = round(1 - nrow(cand) /
                          (as.numeric(nrow(enrol_std)) * nrow(claims_std)), 6))
     true_pairs           found blocking_recall reduction_ratio 
     3.0000e+04      3.0000e+04      1.0000e+00      9.9991e-01 

Pass 1 does most of the work at a very high yield. Pass 2 is the expensive one — it is the only pass that survives a transposed day and month, and it pays for that with most of the candidates. Passes 3 and 4 add the records whose surname or date of birth is simply wrong. This table is the blocking design’s justification; a pass that adds no true pairs should be deleted, and a pass with a very low yield is the one to tighten first.

12.5 Step 4: score each candidate, field by field

A single similarity over a concatenated name hides which field disagreed. Score each field separately and keep the columns, so a reviewer can see why a pair scored what it did. rLink() puts each score next to the pair of columns it scores:

A date of birth deserves better than equal-or-not. The errors it actually carries are a transposed day and month, a year out by one, and the 1 January placeholder — so grade it, and let the weight apply to the grade:

dob_agreement <- function(a, b) {
    da <- fas.Date(a); db <- fas.Date(b)      # comparators are handed text
    pa <- date_parts(da); pb <- date_parts(db)
    ok <- !is.na(da) & !is.na(db)
    gap <- abs(as.numeric(da) - as.numeric(db))
    out <- numeric(length(a))
    # Weakest first; each line overrides the one above it.
    out[which(ok & pa$year == pb$year)]                      <- 0.3
    out[which(ok & pa$year == pb$year & pa$month == pb$month)] <- 0.5
    out[which(ok & gap <= 366)]                              <- 0.7
    out[which(ok & pa$year == pb$year &                      # day/month swap
                   pa$day == pb$month & pa$month == pb$day)]  <- 0.8
    out[which(ok & gap <= 1)]                                <- 0.9
    out[which(ok & da == db)]                                <- 1
    out[!ok] <- 0.5                           # one side missing: no evidence
    out
}
d1 <- c("1985-03-05", "1985-03-14", "1985-03-15", "1985-03-15", "1985-03-15")
d2 <- c("1985-05-03", "1985-03-15", "1986-03-15", "1985-11-02", "1985-03-15")
data.frame(d1, d2, agreement = dob_agreement(d1, d2))
          d1         d2 agreement
1 1985-03-05 1985-05-03       0.8
2 1985-03-14 1985-03-15       0.9
3 1985-03-15 1986-03-15       0.7
4 1985-03-15 1985-11-02       0.7
5 1985-03-15 1985-03-15       1.0
scored <- rLink(
    enrol_std, claims_std,
    block = list(
        list(soundex(surname), dob),
        list(soundex(surname), format_date(dob, "y")),
        list(soundex(given_name), dob),
        list(soundex(surname), fsubstr(given_name, 1, 1), postcode)
    ),
    max_block_size = 2000,
    compare = list(
        surname      = jaro_winkler(surname),
        surname_key  = (function(a, b) as.numeric(a == b))(surname_key),
        given        = jaro_winkler(given_name),
        given_tokens = jaro_winkler_tokens(given_name),
        middle       = (function(a, b)
            ifelse(is.na(a) | is.na(b), 0.5, as.numeric(a == b)))(middle_name),
        dob          = dob_agreement(dob),
        dob_exact    = (function(a, b) as.numeric(a == b))(dob),
        sex          = sex_agree(sex),
        address      = jaro_winkler_tokens(street_address),
        suburb       = jaro_winkler(suburb),
        postcode     = (function(a, b) as.numeric(a == b))(postcode)
    ),
    keep = c("enrol_id", "claim_id", "surname", "given_name", "dob", "sex",
             "street_address", "suburb", "postcode")
)
names(scored)
 [1] "pair_id"          "index_1"          "index_2"          "pass"            
 [5] "block_key"        "enrol_id_1"       "given_name_1"     "given_name_2"    
 [9] "given"            "given_tokens"     "surname_1"        "surname_2"       
[13] "surname"          "dob_1"            "dob_2"            "dob"             
[17] "dob_exact"        "sex_1"            "sex_2"            "sex"             
[21] "street_address_1" "street_address_2" "address"          "suburb_1"        
[25] "suburb_2"         "suburb"           "postcode_1"       "postcode_2"      
[29] "postcode"         "claim_id_2"       "surname_key"      "middle"          

Every carried column takes the suffix of the side it came from, including the ones only one file has: enrol_id is enrol_id_1 and claim_id is claim_id_2. With score_position = "grouped" (the default) each score sits next to the pair of columns it scores, which is what makes a row readable:

scored[1:3, c("enrol_id_1", "claim_id_2", "surname_1", "surname_2", "surname",
              "given_name_1", "given_name_2", "given", "dob_1", "dob_2",
              "dob", "dob_exact")]
   enrol_id_1 claim_id_2 surname_1 surname_2   surname given_name_1
       <char>     <char>    <char>    <char>     <num>       <char>
1:    E000001    C003228  CAMPBELL  CAMPBELL 1.0000000         LELL
2:    E000001    C014597  CAMPBELL  CAMPBELL 1.0000000         LELL
3:    E000001    C000001  CAMPBELL  CAMPLELL 0.9214286         LELL
   given_name_2 given      dob_1      dob_2   dob dob_exact
         <char> <num>     <Date>     <Date> <num>     <num>
1:        LINDA 0.535 1974-07-28 1973-11-07   0.7         0
2:        LINDA 0.535 1974-07-28 1974-08-10   0.7         0
3:         LELL 1.000 1974-07-28 1974-07-28   1.0         1

Every comparator was probed and oriented so that 1 means an exact match, whichever way its own scale runs:

attr(scored, "compare")
          score          comparator       column_1       column_2        scale
1       surname        jaro_winkler        surname        surname   similarity
2   surname_key         <anonymous>    surname_key    surname_key   similarity
3         given        jaro_winkler     given_name     given_name   similarity
4  given_tokens jaro_winkler_tokens     given_name     given_name   similarity
5        middle         <anonymous>    middle_name    middle_name   similarity
6           dob       dob_agreement            dob            dob not detected
7     dob_exact         <anonymous>            dob            dob   similarity
8           sex           sex_agree            sex            sex   similarity
9       address jaro_winkler_tokens street_address street_address   similarity
10       suburb        jaro_winkler         suburb         suburb   similarity
11     postcode         <anonymous>       postcode       postcode   similarity

That matters as soon as you mix families. Adding an edit distance to the list needs no change to the weights:

d <- rLink(enrol_std[1:2000, ], claims_std[1:2000, ],
           block = list(list(soundex(surname), dob)),
           compare = list(jw = jaro_winkler(surname),
                          lev = levenshtein(surname),
                          fz = fuzz_token_set_ratio(surname)),
           keep = "surname")
attr(d, "compare")
  score           comparator column_1 column_2          scale
1    jw         jaro_winkler  surname  surname     similarity
2   lev          levenshtein  surname  surname  edit distance
3    fz fuzz_token_set_ratio  surname  surname similarity/100
head(d[, c("surname_1", "surname_2", "jw", "lev", "fz")], 4)
    surname_1  surname_2    jw   lev    fz
       <char>     <char> <num> <num> <num>
1:     WALKER     WALKER     1     1     1
2:      WHITE      WHITE     1     1     1
3:   BRABORIN   BRABORIN     1     1     1
4: RAGRADASON RAGRADASON     1     1     1

levenshtein() counts edits (0 is identical) and fuzz_token_set_ratio() runs to 100; both come back on the same 0–1 scale as Jaro-Winkler. Set normalise = FALSE to keep each comparator’s own units.

dob_agreement is listed as not detected in the table above, and that is the right answer: the probe is a pair of letter strings, which fas.Date() cannot parse, so nothing can be inferred from it and the scores are passed through untouched. That is harmless here because the function already returns 0–1 with 1 meaning identical. A comparator of your own that does not already run that way should either be written so it does or be left to normalise = FALSE — and the scale column is where you check which happened.

Which fields actually carry information

The weights say how much each field’s agreement is worth, and the data can be asked. For each field, compare its mean score among the pairs that are the same person with its mean among the pairs that are not — the m- and u-probabilities of the Fellegi-Sunter model, which here can be computed exactly because the truth is known:

field_info <- function(column, truth) {
    m <- mean(column[truth]); u <- mean(column[!truth])
    c(agreement_if_match = round(m, 3), agreement_if_not = round(u, 3),
      log_odds = round(log(m / u), 2))
}
truth_c <- same_person(files, scored$index_1, scored$index_2)
t(sapply(list(surname  = pmax(scored$surname, scored$surname_key),
              given    = pmax(scored$given, scored$given_tokens),
              dob      = scored$dob,
              middle   = scored$middle,
              sex      = scored$sex,
              address  = scored$address,
              suburb   = scored$suburb,
              postcode = scored$postcode),
         field_info, truth = truth_c))
         agreement_if_match agreement_if_not log_odds
surname               0.974            0.946     0.03
given                 0.991            0.359     1.02
dob                   0.977            0.691     0.35
middle                0.768            0.332     0.84
sex                   0.966            0.504     0.65
address               0.963            0.531     0.60
suburb                0.953            0.528     0.59
postcode              0.901            0.021     3.74

Two things in that table are worth more than any rule of thumb.

Surname looks useless, and is not. Its log-odds is near zero because every candidate pair already agrees on the surname code or the given-name code — blocking conditioned on it. A field cannot discriminate among pairs that were selected for agreeing on it. This is why the naive move of reading the weights straight off this table misfires, and why a real project fits the model on the pairs it will actually score, with the blocking in the model.

Postcode looks decisive, and is a trap. Its log-odds is the largest in the table, because two unrelated people rarely share a postcode. But the people who moved — one in ten here — disagree on it while being the same person. Weighting it by that log-odds buys precision on the easy pairs and loses exactly the matches that needed help. Address and suburb carry the same risk for the same reason, and the fix is to weight the identifiers that do not change (name, date of birth) far above the ones that do:

w <- c(surname = 3, given = 3, dob = 4, middle = 0.5, sex = 0.5,
       address = 0.75, suburb = 0.25, postcode = 0.5)

scored$score <- with(scored,
    (w["surname"]  * pmax(surname, surname_key) +
     w["given"]    * pmax(given, given_tokens) +
     w["dob"]      * dob +
     w["middle"]   * middle +
     w["sex"]      * sex +
     w["address"]  * address +
     w["suburb"]   * suburb +
     w["postcode"] * postcode) / sum(w))
round(quantile(scored$score, c(0, 0.5, 0.9, 0.99, 1)), 3)
   0%   50%   90%   99%  100% 
0.323 0.647 0.980 1.000 1.000 

pmax(surname, surname_key) is the “either kind of agreement will do” idiom: the Jaro-Winkler score, or 1 if the two fingerprints are identical, whichever is kinder. The same for the two given-name comparators.

Hand weights are fine for a first pass as long as they are written down and swept (below). On real data, estimate them: fastLink and reclin2 fit Fellegi-Sunter weights, including the conditional-independence and blocking subtleties this section only gestures at.

12.6 Step 5: decide, and admit ambiguity

Look at the two score distributions before picking a threshold. If they overlap, no single cut-off is right and the overlap is the review queue.

qs <- c(0.001, 0.01, 0.05, 0.25, 0.5)
round(rbind(same_person = quantile(scored$score[truth_c], qs),
            different   = quantile(scored$score[!truth_c], 1 - qs)), 3)
             0.1%    1%    5%   25%  50%
same_person 0.740 0.851 0.892 0.954 0.98
different   0.815 0.780 0.710 0.667 0.63

Read the second row right to left: the strongest non-matches. Where the weakest true pairs sit above the strongest false ones, a threshold in between separates them cleanly.

sweep <- t(sapply(seq(0.70, 0.95, by = 0.025), function(t) {
    keep <- scored$score >= t
    c(threshold = t, links = sum(keep),
      precision = round(mean(truth_c[keep]), 4),
      recall    = round(sum(truth_c & keep) / true_pair_count(files), 4))
}))
sweep
      threshold links precision recall
 [1,]     0.700 40344    0.7436 1.0000
 [2,]     0.725 34315    0.8743 1.0000
 [3,]     0.750 32340    0.9260 0.9982
 [4,]     0.775 31380    0.9502 0.9939
 [5,]     0.800 30519    0.9770 0.9939
 [6,]     0.825 29859    0.9985 0.9938
 [7,]     0.850 29719    0.9996 0.9902
 [8,]     0.875 29347    0.9999 0.9781
 [9,]     0.900 28289    1.0000 0.9430
[10,]     0.925 25126    1.0000 0.8375
[11,]     0.950 22664    1.0000 0.7555

A two-threshold rule is more honest than one: accept above the upper, reject below the lower, and send the band between them to clerical review. Size that band before promising it to anyone.

accept <- 0.85
review <- 0.78
band   <- scored$score >= review & scored$score < accept
c(accepted     = sum(scored$score >= accept),
  to_review    = sum(band),
  review_share = round(mean(band), 4),
  review_true  = round(mean(truth_c[band]), 3),
  rejected     = sum(scored$score < review))
    accepted    to_review review_share  review_true     rejected 
  29719.0000    1492.0000       0.0089       0.0740  137251.0000 

The band is small — under 1% of the candidates — and most of it is not a match. That is the normal shape of a review queue: it holds the pairs that look like matches on the fields that usually settle it, and a reviewer’s job is mostly to reject them. What the reviewer needs is not the total but the field that disagreed, which is why the scores were kept as separate columns rather than summed away:

hard <- scored[band, ][order(-scored$score[band]), ]
fields <- c("surname", "given", "dob", "sex", "address", "suburb", "postcode")
hard[1:4, c("surname_1", "surname_2", "given_name_1", "given_name_2",
            "dob_1", "dob_2", "score")]
   surname_1 surname_2 given_name_1 given_name_2      dob_1      dob_2
      <char>    <char>       <char>       <char>     <Date>     <Date>
1: HOBASTROS     BROWN       SOPHIE       SOPHIE 1982-05-17 1982-05-17
2:  ROBINSON  ROBINSON     PATRICIA           PI 1971-06-18 1971-06-18
3:   SEMIKES    BUKIDU        SARAH        SARAH 1961-10-24 1961-10-24
4:   BUHADAR    MARULL         EMMA         EMMA 1944-04-22 1944-04-22
       score
       <num>
1: 0.8497778
2: 0.8496984
3: 0.8495238
4: 0.8495238
round(as.matrix(hard[1:4, ..fields]), 2)
     surname given dob sex address suburb postcode
[1,]    0.37  1.00   1   1    1.00   1.00        1
[2,]    1.00  0.78   1   1    0.55   0.52        0
[3,]    0.37  1.00   1   1    1.00   1.00        1
[4,]    0.37  1.00   1   1    1.00   1.00        1

And when it is a name that disagrees, edit_ops() turns the distance back into the edits that produced it:

i <- which(hard$given < 1)[1]          # the first pair whose names disagree
hard[i, c("surname_1", "surname_2", "given_name_1", "given_name_2")]
   surname_1 surname_2 given_name_1 given_name_2
      <char>    <char>       <char>       <char>
1:  ROBINSON  ROBINSON     PATRICIA           PI
edit_ops(hard$given_name_1[i], hard$given_name_2[i], type = "opcodes")
  pair   type a_start a_end b_start b_end
1    1  equal       1     1       1     1
2    1 delete       2     4       2     1
3    1  equal       5     5       2     2
4    1 delete       6     8       3     2

12.7 Step 6: entity identifiers

Downstream work wants one identifier per person, not a list of pairs. cluster_pairs() takes the transitive closure of the accepted pairs; offset the second file’s indices so both files share one numbering:

n1 <- nrow(enrol_std)
entity <- cluster_pairs(best$index_1, best$index_2 + n1,
                        n = n1 + nrow(claims_std))
enrol_std$entity_id  <- entity[seq_len(n1)]
claims_std$entity_id <- entity[n1 + seq_len(nrow(claims_std))]

c(entities = max(entity), records = length(entity))
entities  records 
   57792    87500 
table(cluster_size = tabulate(entity))
cluster_size
    1     2 
28084 29708 

Clusters larger than two mean a record was linked to more than one on the other side, or a chain formed. With a one-to-one resolution they cannot appear; without one, inspect them before trusting them.

Finally, pseudonymise the identifiers if the linked file is going anywhere. fhash() with a keyed HMAC is stable across runs with the same key and not reversible without it (sec-uc-privacy):

key <- "a-secret-held-by-the-data-custodian"
head(fhash(sprintf("ENT%07d", unique(entity)), algo = "sha256", key = key), 3)
[1] "376e020d19383f1d78e489d31f620c4053a0830a1677779f4280f2b9d7bc4759"
[2] "95f477ca0f8543c421efdfd5fd00a761ae9643e696dfff9edd5d9315f06df05e"
[3] "e1564331a3a4b0c9267cdcd25af29890a494e678a788b2352549337e36c4ceb4"

12.8 Step 7: what it cost, and what the fast versions bought

c(enrol = nrow(enrol_std), claims = nrow(claims_std),
  true_pairs = true_pair_count(files),
  pairs_compared = nrow(scored),
  blocking_recall = round(sum(truth_c) / true_pair_count(files), 4),
  precision = round(mean(same_person(files, best$index_1, best$index_2)), 4),
  recall = round(sum(same_person(files, best$index_1, best$index_2)) /
                 true_pair_count(files), 4))
          enrol          claims      true_pairs  pairs_compared blocking_recall 
     50000.0000      37500.0000      30000.0000     168462.0000          1.0000 
      precision          recall 
         0.9999          0.9902 

attr(scored, "timings") says where the time actually went, stage by stage — the key stage once per record, the comparators once per pair:

attr(scored, "timings")
          stage      seconds
1      validate 9.894371e-05
2          keys 1.223309e-01
3         pairs 3.779507e-02
4        attach 1.805370e-01
5       surname 7.751942e-03
6   surname_key 1.365590e-02
7         given 7.012844e-03
8  given_tokens 1.234198e-02
9        middle 2.732801e-02
10          dob 1.246049e-01
11    dob_exact 1.821041e-03
12          sex 1.020813e-02
13      address 4.100895e-02
14       suburb 6.666183e-03
15     postcode 4.688025e-03
16     assemble 1.897812e-04
17        total 5.990129e-01

The standardising in step 2 is a dozen passes over a column each. At 37,500 rows none of them is measurable, so here they are on a million — the size at which the choice starts to matter — against the base R equivalent:

ms <- function(f, reps = 3) {
    f()                                    # warm up
    start <- Sys.time()
    for (i in seq_len(reps)) f()
    round(1000 * (as.numeric(Sys.time()) - as.numeric(start)) / reps, 1)
}
bench <- function(label, fast, base = NULL) {
    f <- ms(fast)
    b <- if (is.null(base)) NA_real_ else ms(base)
    data.frame(step = label, fast_ms = f, base_ms = b,
               ratio = if (is.na(b)) NA_real_ else round(b / f, 1))
}
big_name <- rep_len(claims$patient_name, 1e6)
big_date <- rep_len(claims$date_of_birth, 1e6)
big_dob  <- rep_len(dob, 1e6)
big_surn <- rep_len(claims_std$surname, 1e6)

do.call(rbind, list(
    bench("upper-case the name",
          function() fupper(big_name), function() toupper(big_name)),
    bench("squish whitespace",
          function() fsquish(big_name),
          function() gsub("[[:space:]]+", " ", trimws(big_name))),
    bench("split on the comma",
          function() fsplit_field(big_name, ",", 1),
          function() vapply(strsplit(big_name, ",", fixed = TRUE), `[`, "", 1L)),
    bench("parse the date of birth",
          function() fas.Date(big_date, format = "dmy"),
          function() as.Date(big_date, format = "%d/%m/%Y")),
    bench("write a Date back as text",
          function() format_date(big_dob),
          function() format(big_dob, "%Y-%m-%d")),
    bench("count vowels per name",
          function() fcount("[AEIOU]", big_name),
          function() lengths(regmatches(big_name,
                                        gregexpr("[AEIOU]", big_name)))),
    bench("Soundex of the surname", function() soundex(big_surn)),
    bench("Jaro-Winkler, a million pairs",
          function() jaro_winkler(big_surn, rev(big_surn)))
))
                           step fast_ms base_ms ratio
1           upper-case the name    92.3   816.5   8.8
2             squish whitespace    43.1   964.3  22.4
3            split on the comma    62.7   587.8   9.4
4       parse the date of birth     8.3  3174.1 382.4
5     write a Date back as text    34.3  5341.1 155.7
6         count vowels per name    15.5  5394.1 348.0
7        Soundex of the surname    28.1      NA    NA
8 Jaro-Winkler, a million pairs    22.6      NA    NA

The wins are uneven, and that is the honest picture. The biggest ones are where base R is doing something structurally expensive: a strptime() and a strftime() per element for the dates, a strsplit() that allocates a list of pieces only to take one and throw the rest away, a gregexpr() that allocates a position vector per row only to take its length. Where base R is already doing one cheap pass in C, the gain is small — and sec-benchmarks lists the cases where base R is the faster choice outright.

The last two rows have no base R equivalent at all, which is the other half of the argument: the phonetic key and the similarity score are what make blocking and scoring possible in the first place, and the pipeline above is built out of them.