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:
Standardise the fields you compare (sec-uc-clean).
Generate candidate pairs cheaply, so that only plausible pairs are compared in detail: blocking, the sorted neighbourhood method, or a similarity search.
Score each candidate pair, field by field.
Decide which pairs are matches.
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.
Everything below works on the same pair of files: an enrolment extract and a claims extract that hold the same people, recorded by two systems that agree about nothing except who those people are. docs/_people.R in the repository builds them, with a person_id kept aside so every claim in this chapter can be checked rather than asserted.
The claims file is the awkward one, and awkward in all the usual ways: the whole name in one "SURNAME, Title Given Middle" field in title case with doubled and trailing spaces, the date of birth as "DD/MM/YYYY" text, sex spelled out (and sometimes blank), the address as one line with abbreviated street types and a unit prefix, and a numeric postcode, so 0823 arrived as 823.
sec-workflow standardises it field by field. For now, here it is in one block, so that the examples below have two files with the same column names and the same types:
titles<-c("MR", "MRS", "MS", "MISS", "DR", "PROF")street_abbrev<-c("ST", "RD", "AVE", "CT", "PL", "TCE", "PDE", "CRES", "DR", "LN")street_full<-c("STREET", "ROAD", "AVENUE", "COURT", "PLACE", "TERRACE","PARADE", "CRESCENT", "DRIVE", "LANE")name<-fsquish(fupper(claims$patient_name))# one pass, no case leftrest<-fsquish(freplace_tokens(ftrimws(fsplit_field(name, ",", 2)),titles, rep("", length(titles))))addr<-fgsub("^U[0-9]+/", "", fupper(claims$address_line))# drop the unit prefixclaims_std<-data.frame( claim_id =claims$claim_id, given_name =fsplit_field(rest, " ", 1), middle_name =fsplit_field(rest, " ", 2), surname =ftrimws(fsplit_field(name, ",", 1)), dob =fas.Date(claims$date_of_birth, format ="dmy"), sex =c(Male ="M", Female ="F", Unknown ="U")[claims$gender], street_address =fsquish(freplace_tokens(ftrimws(fsplit_field(addr, ",", 1)),street_abbrev, street_full)), suburb =ftrimws(fgsub(" VIC$", "", fsplit_field(addr, ",", 2))), postcode =fpad(as.character(claims$postcode), 4, pad ="0"), stringsAsFactors =FALSE)claims_std$sex[is.na(claims_std$sex)]<-"U"# The enrolment file keeps its address in parts; join them the same way.enrol$street_address<-fsquish(paste(enrol$number, enrol$street,enrol$street_type))head(claims_std, 4)
claim_id given_name middle_name surname dob sex street_address
1 C014234 STRODULL DACLELL MOORE 2011-08-04 F 399 QUEEN LANE
2 C004667 WEI GABOLL MAJAN 2017-03-30 M 376 FLINDERS AVENUE
3 C004718 HOLOR TEKOSON SANOR 1977-09-20 F 85 KING STREET
4 C013920 MARIA SARAH THOMPSPN 1989-08-09 F 433 FOREST STREET
suburb postcode
1 FOOTSCRAY 3093
2 RICHMOND 0842
3 BRUNSWICK 3193
4 ST KILDA 3095
6.2 Blocking and scoring in one call: rLink()
rLink() takes the two data frames, a list of blocking passes, and a list of comparators, and returns one row per candidate pair with the compared columns side by side and a score column for each comparator. Blocking keys and comparison fields are written as ordinary R expressions evaluated against the data, so a phonetic code or a date part goes in the call rather than into a column prepared beforehand:
pair_id index_1 index_2 pass block_key enrol_id_1 given_name_1
<int> <int> <int> <int> <char> <char> <char>
1: 1 2 8120 3 B616|2014-01-07 E000002 BARBARA
2: 2 3 495 2 W452|1965 E000003 MEHAEZ
3: 3 3 2946 1 W452|1965-12-25 E000003 MEHAEZ
given_name_2 given surname_1 surname_2 surname
<char> <num> <char> <char> <num>
1: BARBARA 1.00 WARD DEPREGILL 0.4074074
2: MARY 0.65 WILLIAMS WILLIAMS 1.0000000
3: MEHAEZ 1.00 WILLIAMS WILLIAMS 1.0000000
The outer list() separates passes; a pair is a candidate if it agrees on any one pass, each pair is reported once, and pass records the first pass that found it. Inside a pass, list() joins terms into one key, so list(soundex(surname), dob) requires the same surname code and the same date of birth. A comparator’s first argument names the column to compare; anything else is its own options. Any function of two character vectors works, which is how sex and the exact dob/postcode comparisons above are written inline.
Three things are worth knowing straight away.
Scores are oriented for you. Comparators disagree about which end of their scale means “identical”: jaro_winkler() returns 1, levenshtein() returns 0, the RapidFuzz fuzz_*() scorers return 100. rLink() probes each one on a calibration pair and converts, so 1 always means an exact match. What it found is recorded, and is worth reading once:
score comparator column_1 column_2 scale
1 surname jaro_winkler surname surname similarity
2 given jaro_winkler_tokens given_name given_name similarity
3 dob <anonymous> dob dob similarity
4 sex <anonymous> sex sex similarity
5 address jaro_winkler_tokens street_address street_address similarity
6 suburb jaro_winkler suburb suburb similarity
7 postcode <anonymous> postcode postcode similarity
direction n_scored
1 higher 34282
2 higher 34282
3 higher 34282
4 higher 34282
5 higher 34282
6 higher 34282
7 higher 34282
Comparators see text. Every comparison column is converted to character first, so a Date reaches the comparator as "YYYY-MM-DD". Exact agreement therefore just works, but a tolerance needs the date back:
Because pass records the pass that found each pair, and because these files come with a known truth, each pass can be audited for what it actually contributed:
Blocking found every true pair in the data while comparing 34,282 of the 300,000,000 possible ones. The pass table also shows what each pass costs: pass 2 (surname code plus year of birth) generates most of the candidates for a few hundred extra matches. It is the pass that survives a transposed day and month, so it earns its place – but it is the one to tighten first if the run gets too big, with max_block_size or a narrower key.
Deciding, and clustering
Combine the score columns however your project justifies – hand weights here, a Fellegi-Sunter model in fastLink or reclin2 on real data – and look at the two distributions before picking a threshold:
cand$score<-with(cand,(3*surname+2*given+2*dob+0.5*sex+address+suburb+postcode)/10.5)qs<-c(0.01, 0.05, 0.5, 0.95)round(rbind(same_person =quantile(cand$score[truth], qs), different =quantile(cand$score[!truth], qs)), 3)
The two are well separated: the weakest 1% of true pairs still score above the strongest 5% of false ones, so a threshold anywhere in the gap is defensible.
Then turn the accepted pairs into entity identifiers. cluster_pairs() joins records connected by any chain of matches (the connected components of the match graph); offset the second file’s indices so the two files share one numbering:
links<-cand[cand$score>=0.78, ]entity<-cluster_pairs(links$index_1, links$index_2+nrow(enrol), n =nrow(enrol)+nrow(claims_std))table(cluster_size =tabulate(entity))
cluster_size
1 2 3
11155 11921 1
Chaining is also the risk: if A and C do not match directly, their cluster rests on B. Look at the largest clusters before trusting them, or raise the threshold for pairs that would join two already-large clusters.
Deduplicating one file
With one data frame, rLink() deduplicates it: pairs come back with index_1 < index_2 and no record paired with itself. Here the two files arrive stacked, as a single extract, and the job is to find the people who appear twice:
source_1 source_2 surname_1 surname_2 given_name_1 given_name_2 dob_1
<char> <char> <char> <char> <char> <char> <Date>
1: enrol claims WILLIAMS WILLIAMS MEHAEZ MEHAEZ 1965-12-25
2: enrol claims SMITH SMITH PETER PETER 1952-11-28
3: enrol claims MOTIFES MOTIFES TRIS TRIS 1973-11-10
4: enrol claims THOMPSON THOMPSON FELER FELER 1992-09-14
given surname
<num> <num>
1: 1 1
2: 1 1
3: 1 1
4: 1 1
Scoring pairs you found some other way
pairs takes candidate pairs from anywhere instead of blocking – any data frame with x_index and y_index, which is the shape minhash_pairs(), fuzzy_within() and tfidf_top_n() all return:
pair_id index_1 index_2 pass surname_1 surname_2 surname dob_1
<int> <int> <int> <int> <char> <char> <num> <Date>
1: 1 1 7 NA KING TAYLOR 0.0000000 1962-12-15
2: 2 2 7 NA WARD TAYLOR 0.4722222 2014-01-07
3: 3 3 9 NA WILLIAMS MACDONALD 0.4120370 1965-12-25
dob_2
<Date>
1: 1968-11-10
2: 1968-11-10
3: 1986-05-26
Columns named differently in the two files
compare takes column_1 | column_2 when the two files call the same thing by different names, and block_2 gives the second file its own blocking expressions, pass for pass:
index_1 index_2 pass block_key surname_1 surname_raw_2 sn
<int> <int> <int> <char> <char> <char> <num>
1: 1 333 1 K520 KING KING 1
2: 1 398 1 K520 KING KING 1
3: 1 433 1 K520 KING KING 1
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:
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)))
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:
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.
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:
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:
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:
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:
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)
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)
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 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)
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$claimsnm<-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$enrolsystem.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()))
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.