6  Match, deduplicate and link records

Record linkage – finding the records that refer to the same person, business or address, within one file or across several – has the same shape whatever the data:

  1. Standardise the fields you compare (sec-uc-clean).
  2. Generate candidate pairs cheaply, so that only plausible pairs are compared in detail: blocking, the sorted neighbourhood method, or a similarity search.
  3. Score each candidate pair, field by field.
  4. Decide which pairs are matches.
  5. Cluster the matched pairs into entities.

rLink() does steps 2 and 3 in one call. The rest of this chapter is the toolbox underneath it, for the cases where you want to drive each stage yourself. sec-workflow takes a messy pair of files all the way through, including the standardising and the decision.

For rLink() itself — worked from the simplest useful call up to a staged production linkage of people, field by field — see sec-rlink, and sec-rlink-inspect for reviewing the pairs it cannot settle.

Stage Functions
Blocking and scoring in one call rLink()
Candidate pairs from keys block_pairs(), sorted_neighbourhood()
Phonetic keys soundex(), nysiis(), metaphone(), double_metaphone(), daitch_mokotoff(), statcan(), phonex(), onca(), caverphone(), …
Candidates by similarity search fuzzy_within(), tfidf_top_n(), tfidf_match(), minhash_pairs(), fuzzy_top_n()
Scoring jaro_winkler(), jaro_winkler_tokens(), editex(), monge_elkan(), smith_waterman(), lcs_str(), levenshtein(), fuzz_*()
Explaining a score edit_ops()
Entities from matches cluster_pairs()

6.3 Candidate pairs by blocking, by hand

block_pairs() is the blocking engine rLink() calls, and is what to reach for when you want the pairs without the scoring – to count them first, or to feed them somewhere else. It takes one column per pass:

block_keys <- function(d) data.frame(
    surname_dob = paste(soundex(d$surname), d$dob),
    dob         = as.character(d$dob),
    initial_pc  = paste(fsubstr(d$given_name, 1, 1), d$postcode))

p <- block_pairs(block_keys(enrol), block_keys(claims_std))
nrow(p)
[1] 86714
table(pass = p$pass)
pass
    1     2     3 
 9797 10759 66158 

A missing key (NA) never pairs with anything, which is what makes blocking on an incomplete field safe: the records with no date of birth simply do not appear in the passes that use it.

max_block_size skips blocks too big to be worth comparing – the commonest surname code, or the 1 January placeholder date – and warns with how many it dropped. How big a block gets is worth measuring before you decide:

sizes <- table(soundex(enrol$surname))
c(blocks = length(sizes), largest = max(sizes), over_400 = sum(sizes > 400))
  blocks  largest over_400 
    1625      582        5 
# A surname-only pass, capped. A handful of codes go, and with them more
# than half the pairs the pass would have produced.
nrow(block_pairs(soundex(enrol$surname), soundex(claims_std$surname)))
[1] 1865586
nrow(block_pairs(soundex(enrol$surname), soundex(claims_std$surname),
                 max_block_size = 400))
[1] 755271

6.4 The sorted neighbourhood method

Exact keys miss pairs whose keys differ in the last characters (SMITH and SMITHE). sorted_neighbourhood() sorts the distinct key values and pairs records whose values are within (window - 1) / 2 places of each other, as well as records with equal values. A second pass on the reversed key catches errors at the start of the string:

surname <- c("SMITH", "SMITHE", "SMYTH", "JONES", "JONSON", "XMITH")
p <- sorted_neighbourhood(data.frame(surname, freverse(surname)), window = 3)
data.frame(a = surname[p$x_index], b = surname[p$y_index], pass = p$pass)
       a      b pass
1  SMITH SMITHE    1
2  SMITH JONSON    1
3  SMITH  XMITH    2
4 SMITHE  SMYTH    1
5  SMYTH JONSON    2
6  SMYTH  XMITH    1
7  JONES JONSON    1

XMITH only meets SMITH in the reversed pass. Note what else the window pairs: SMITH with JONSON, because they are alphabetical neighbours, not because they are alike. The method trades precision for recall by design, so it belongs in a pass whose candidates are then scored, never on its own. The window moves over distinct values, as in Python’s recordlinkage package, so the pairs do not depend on the order of the records and every tie is paired. Keys can be dates or numbers too: a date of birth with window = 3 pairs dates one day apart, which is exactly the transcription error that format_date(dob, "y") above needed a whole extra pass to survive.

d <- as.Date(c("1985-03-14", "1985-03-15", "1985-03-16", "1990-01-01"))
sorted_neighbourhood(d, window = 3)
  x_index y_index pass
1       1       2    1
2       2       3    1
3       3       4    1

rLink(block_method = "sorted_neighbourhood", window = 3) uses it for every pass of a linkage.

6.5 Choose phonetic keys by how much they merge

Every phonetic code merges some spellings and separates others, and the trade-off is block size against recall. Comparing codes on the name variants you actually expect shows the differences quickly:

surn <- c("SMITH", "SMYTH", "SCHMIDT", "MEYER", "MEIER", "MCDONALD",
          "MACDONALD", "THOMPSON", "TOMSON", "NGUYEN", "NGYUEN", "PHILLIPS",
          "FILLIPS", "O'BRIEN", "OBRIEN", "BRIEN")
codes <- data.frame(name = surn, soundex = soundex(surn), nysiis = nysiis(surn),
                    metaphone = metaphone(surn), statcan = statcan(surn),
                    phonex = phonex(surn), onca = onca(surn),
                    caverphone = caverphone(surn))
codes
        name soundex nysiis metaphone statcan phonex onca caverphone
1      SMITH    S530   SNAT       SM0    SMTH   S530 S530 SMT1111111
2      SMYTH    S530   SNYT       SM0    SMTH   S530 S530 SMT1111111
3    SCHMIDT    S530   SNAD      SKMT    SCHM   S253 S530 SKMT111111
4      MEYER    M600  MAYAR       MYR      MR   M600 M600 MA11111111
5      MEIER    M600    MAR        MR      MR   M600 M600 MA11111111
6   MCDONALD    M235 MCDANA      MKTN    MCDN   M235 M235 MKTNT11111
7  MACDONALD    M235 MCDANA      MKTN    MCDN   M235 M235 MKTNT11111
8   THOMPSON    T512 TANPSA      0MPS    THMP   T512 T512 TMPSN11111
9     TOMSON    T525 TANSAN      TMSN    TMSN   T525 T525 TMSN111111
10    NGUYEN    N250 NGAYAN      NKYN     NGN   N250 N250 NKN1111111
11    NGYUEN    N250  NGYAN      NJYN     NGN   N250 N250 NKN1111111
12  PHILLIPS    P412  FALAP      FLPS    PHLP   F410 F410 FLPS111111
13   FILLIPS    F412  FALAP      FLPS    FLPS   F410 F410 FLPS111111
14   O'BRIEN    O165  OBRAN      OBRN    OBRN   A165 O165 APRN111111
15    OBRIEN    O165  OBRAN      OBRN    OBRN   A165 O165 APRN111111
16     BRIEN    B650   BRAN       BRN     BRN   B650 B650 PRN1111111
sapply(codes[-1], function(k) length(unique(k)))   # fewer = coarser blocks
   soundex     nysiis  metaphone    statcan     phonex       onca caverphone 
        10         13         12         11         10          9         10 

Soundex merges SCHMIDT with SMITH but separates PHILLIPS from FILLIPS; Phonex and ONCA join the latter pair. NYSIIS and Metaphone separate more spellings, which makes smaller blocks and needs more passes. Caverphone was designed for New Zealand and Australian electoral-roll names.

The same comparison on your own file, rather than on a list of variants, says how big the blocks will be:

sizes <- sapply(list(exact = enrol$surname, soundex = soundex(enrol$surname),
                     nysiis = nysiis(enrol$surname), phonex = phonex(enrol$surname),
                     dmetaphone = double_metaphone(enrol$surname)$primary),
                function(k) c(blocks = length(unique(k)),
                              largest = max(tabulate(match(k, unique(k)))),
                              pairs_per_1k = round(sum(tabulate(match(k, unique(k)))^2) /
                                                   length(k) / 1000, 1)))
sizes
              exact soundex nysiis phonex dmetaphone
blocks       4108.0  1625.0 2644.0 1057.0     2422.0
largest       569.0   582.0  583.0  615.0      569.0
pairs_per_1k    0.1     0.1    0.1    0.2        0.1

pairs_per_1k is the number of candidate pairs, in thousands, that the key alone would generate against a file of the same size – the number that decides whether a pass is affordable.

Names from more than one language tradition need more than one code. daitch_mokotoff() returns up to several codes per name, so a name with an ambiguous pronunciation lands in every block it might belong to:

daitch_mokotoff(c("SCHWARZ", "SHVARTZ", "MOSKOWITZ", "MOSKOVITZ"))
[[1]]
[1] "474000" "479400"

[[2]]
[1] "479400"

[[3]]
[1] "645740"

[[4]]
[1] "645740"

The Match Rating Approach is designed as a comparison rather than a key: mra_compare() says whether two names match under its rules.

mra_compare(c("SMITH", "BYRNE", "CATHERINE"), c("SMYTH", "BOERN", "KATHRYN"))
[1] TRUE TRUE TRUE

6.6 Candidates without blocking keys

When there is no good key, search for similar strings directly; none of these functions builds the full comparison matrix.

fuzzy_within() returns every table entry within k edits of each query, using SymSpell’s symmetric-delete index – the right tool for checking typed values against a reference list such as a street or suburb gazetteer:

gazetteer <- sort(unique(enrol$suburb))
typed <- c("RICHMOND", "FITZROI", "ST KILDAA", "CAMBERWEL", "NOWHERE")
w <- fuzzy_within(typed, gazetteer, max_distance = 2)
data.frame(typed = typed[w$query_index], suburb = gazetteer[w$table_index],
           distance = w$distance)
      typed     suburb distance
1  RICHMOND   RICHMOND        0
2   FITZROI    FITZROY        1
3 ST KILDAA   ST KILDA        1
4 CAMBERWEL CAMBERWELL        1

Results come ordered by distance, so the first row per query is the best, and NOWHERE returns nothing rather than a wrong answer. The result is exact – the same pairs as filtering a full osa_distance_matrix() – at a fraction of the cost for large tables.

For names that differ by whole words – an organisation with and without THE, UNI for UNIVERSITY, an extra department – edit distance is the wrong measure. tfidf_match() compares TF-IDF-weighted character n-grams, so rare, informative words dominate and common ones barely count:

orgs <- c("UNIVERSITY OF QUEENSLAND", "QUEENSLAND UNIVERSITY OF TECHNOLOGY",
          "GRIFFITH UNIVERSITY", "QUEENSLAND HEALTH", "BRISBANE CITY COUNCIL",
          "LOGAN CITY COUNCIL", "UNIVERSITY OF SYDNEY")
qs <- c("THE UNIVERSITY OF QUEENSLAND", "QLD UNIVERSITY OF TECHNOLOGY",
        "BRISBANE CITY COUNCIL LIBRARIES", "GRIFFITH UNI", "SYDNEY UNIVERSITY")
data.frame(query = qs, match = orgs[tfidf_match(qs, orgs)])
                            query                               match
1    THE UNIVERSITY OF QUEENSLAND            UNIVERSITY OF QUEENSLAND
2    QLD UNIVERSITY OF TECHNOLOGY QUEENSLAND UNIVERSITY OF TECHNOLOGY
3 BRISBANE CITY COUNCIL LIBRARIES               BRISBANE CITY COUNCIL
4                    GRIFFITH UNI                 GRIFFITH UNIVERSITY
5               SYDNEY UNIVERSITY                UNIVERSITY OF SYDNEY
tfidf_top_n("QLD UNIVERSITY OF TECHNOLOGY", orgs, top_n = 3)
  query_index table_index     score rank
1           1           2 0.8001508    1
2           1           7 0.3253862    2
3           1           1 0.3249688    3

For long text – product descriptions, case notes, addresses with free-text additions – minhash_pairs() finds pairs whose q-gram sets probably overlap by at least threshold (Jaccard), using locality-sensitive hashing, and verifies each candidate exactly.

notes <- c("Unit 4, 9 King St Brisbane - deliver to rear entrance",
           "U4 9 King Street, Brisbane (rear entrance delivery)",
           "12 Logan Road Woolloongabba, upstairs office",
           "12 Logan Rd, Woolloongabba - upstairs office suite",
           "88 Gympie Road Chermside")
minhash_pairs(notes, threshold = 0.4)
  x_index y_index   jaccard
1       1       2 0.4925373
2       3       4 0.6071429

6.7 Score with the comparison that fits the field

Jaro-Winkler is the standard for short names, but each kind of field has its own kind of difference. sec-uc-metrics measures every comparator in the package against labelled name and address pairs and says which to reach for when; the short version is below.

Phonetic misspellings (PH/F, C/K) cost less under editex(), an edit distance whose substitution cost depends on whether the letters sound alike:

a <- c("PHILIP", "CATHERINE", "SHEPHERD", "STEPHEN")
b <- c("FILIP", "KATHRYN", "SHEPPARD", "STEVEN")
data.frame(a, b, levenshtein = round(levenshtein_similarity(a, b), 3),
           editex = round(editex_similarity(a, b), 3))
          a        b levenshtein editex
1    PHILIP    FILIP       0.667  0.750
2 CATHERINE  KATHRYN       0.556  0.722
3  SHEPHERD SHEPPARD       0.750  0.812
4   STEPHEN   STEVEN       0.714  0.786

Multi-word names with reordered, missing or extra words suit monge_elkan() (the mean best match of each word) or jaro_winkler_tokens(). This is the comparison to use on a name field that was never split:

a <- c("JOHN PAUL SMITH", "MARY JANE O BRIEN", "ROBERT JONES", "LI WEI CHEN")
b <- c("SMITH JOHN", "OBRIEN MARY", "BOB JONES", "CHEN LI WEI")
data.frame(a, b,
           jaro_winkler = round(jaro_winkler(a, b), 3),
           monge_elkan  = round(monge_elkan(a, b), 3),
           tokens       = round(jaro_winkler_tokens(a, b), 3))
                  a           b jaro_winkler monge_elkan tokens
1   JOHN PAUL SMITH  SMITH JOHN        0.500       0.667  0.667
2 MARY JANE O BRIEN OBRIEN MARY        0.566       0.799  0.567
3      ROBERT JONES   BOB JONES        0.706       0.789  0.750
4       LI WEI CHEN CHEN LI WEI        0.570       1.000  1.000

Plain Jaro-Winkler is the wrong tool on every row here. monge_elkan() holds up best when a word is missing (JOHN PAUL SMITH against SMITH JOHN) or replaced by a nickname (ROBERT / BOB), because it scores each word against its own best partner and averages; jaro_winkler_tokens() is the stronger of the two on a clean reordering, and it also folds punctuation and spacing, which is what rescues O BRIEN / OBRIEN. Neither recovers a name whose words were both reordered and split differently — row 2 — which is the case for comparing the parsed surname and given_name fields separately instead.

One string inside another – a street address inside a full address line – is local alignment: smith_waterman() scores the best-matching substring, and lcs_str() returns the longest common substring:

smith_waterman(c("9 KING ST", "9 KING ST"),
               c("UNIT 4 9 KING ST BRISBANE", "19 KINGS ST"))
[1] 1.0000000 0.9444444
lcs_str("9 KING ST", "UNIT 4 9 KING ST BRISBANE")
[1] "9 KING ST"

A date of birth is not a string: compare the day numbers, so that 2 January and 1 January are one apart rather than two characters apart.

d1 <- as.Date(c("1985-03-14", "1985-03-05", "1985-03-15", "1985-03-15"))
d2 <- as.Date(c("1985-03-15", "1985-05-03", "1986-03-15", "1985-03-15"))
# date_parts() splits both sides in one pass, which is cheaper than
# formatting them and much cheaper than three format() calls each.
pa <- date_parts(d1)
pb <- date_parts(d2)
data.frame(d1, d2,
           days_apart = abs(as.numeric(d1 - d2)),
           transposed = pa$year == pb$year & pa$day == pb$month &
                        pa$month == pb$day & pa$day != pa$month,
           same_year_month = pa$year == pb$year & pa$month == pb$month)
          d1         d2 days_apart transposed same_year_month
1 1985-03-14 1985-03-15          1      FALSE            TRUE
2 1985-03-05 1985-05-03         59       TRUE           FALSE
3 1985-03-15 1986-03-15        365      FALSE           FALSE
4 1985-03-15 1985-03-15          0      FALSE            TRUE

When a pair goes to clerical review, edit_ops() explains a distance as the edits themselves:

edit_ops("JONATHAN", "JONHATAN", type = "opcodes")
  pair   type a_start a_end b_start b_end
1    1  equal       1     3       1     3
2    1 insert       4     3       4     4
3    1  equal       4     5       5     6
4    1 delete       6     6       7     6
5    1  equal       7     8       7     8

6.8 From matched pairs to entities

Deduplication needs one identifier per entity, not a list of pairs. cluster_pairs() joins records connected by any chain of matches:

# 1 matches 2, 2 matches 3, 4 matches 5; record 6 matches nothing
cluster_pairs(c(1, 2, 4), c(2, 3, 5), n = 6)
[1] 1 1 1 2 2 3

It takes the pair table directly, so the usual last line of a deduplication is one call. On the stacked extract above:

accepted <- dup[dup$given > 0.85 & dup$surname > 0.85, ]
entity <- cluster_pairs(accepted, n = nrow(combined))
c(records = length(entity), entities = max(entity),
  merged = length(entity) - max(entity))
 records entities   merged 
   35000    24763    10237 
table(cluster_size = tabulate(entity))
cluster_size
    1     2 
14526 10237 

Chaining is the risk, and it is visible right there. The stacked extract holds each shared person exactly twice, so a perfect deduplication would leave clusters of size 1 and 2 only. The clusters of eight and thirteen are not people recorded thirteen times; they are chains, where A matched B, B matched C, and nothing ever compared A with C. Three defences, in order of how much work they are:

  • resolve the pairs one-to-one before clustering, keeping each record’s single best partner (sec-workflow does this);
  • raise the threshold for a pair that would join two already-large clusters;
  • review the largest clusters by hand. There are few of them, and they are where the wrong merges live.

A cluster is only as sound as its weakest accepted pair, so it is the minimum pair score inside a large cluster that is worth looking at, not the average.

6.9 At scale

The whole of the linkage above – four blocking passes and seven comparators over 20,000 enrolment records and 15,000 claims – is one rLink() call. The same call on ten times the data:

big <- people_files(n_enrol = 200000, overlap = 0.6)
big_claims <- big$claims
nm <- fsquish(fupper(big_claims$patient_name))
rs <- fsquish(freplace_tokens(ftrimws(fsplit_field(nm, ",", 2)),
                              titles, rep("", length(titles))))
big_std <- data.frame(
    given_name = fsplit_field(rs, " ", 1),
    surname    = ftrimws(fsplit_field(nm, ",", 1)),
    dob        = fas.Date(big_claims$date_of_birth, format = "dmy"),
    postcode   = fpad(as.character(big_claims$postcode), 4, pad = "0"),
    stringsAsFactors = FALSE)
big_enrol <- big$enrol

system.time(
    out <- rLink(big_enrol, big_std,
        block = list(list(soundex(surname), dob),
                     list(soundex(given_name), dob),
                     list(soundex(surname), fsubstr(given_name, 1, 1), postcode)),
        compare = list(surname = jaro_winkler(surname),
                       given   = jaro_winkler_tokens(given_name),
                       dob     = (function(a, b) a == b)(dob)),
        keep = character())
)
   user  system elapsed 
   1.21    0.09    0.81 
c(records_a = nrow(big_enrol), records_b = nrow(big_std),
  pairs_possible = as.numeric(nrow(big_enrol)) * nrow(big_std),
  pairs_compared = nrow(out),
  blocking_recall = round(sum(same_person(big, out$index_1, out$index_2)) /
                          true_pair_count(big), 4))
      records_a       records_b  pairs_possible  pairs_compared blocking_recall 
         200000          150000     30000000000          179127               1 

keep = character() carries none of the input columns onto the output, which is what you want once the pipeline is no longer being read by eye: the indices and the scores are enough to join back.