13  Function reference

Every exported function, grouped the same way as the README. Each entry gives the signature, every argument, the return value, and at least one runnable example. This chapter is the detailed reference; sec-quickstart is the faster tour.

13.1 Matching & substitution

fgrepl()

Equivalent to base::grepl(), using PCRE2 and Intel TBB. Large inputs can use multiple cores; the crossover depends on subject length and pattern cost. See sec-theory for how perl = FALSE follows base R’s default regex rules and how non-ASCII text is matched. With fixed = TRUE, the byte-oriented pattern is prepared once: one-byte needles use memchr, two- and three-byte needles use memchr plus memcmp, and longer needles use Boyer–Moore–Horspool. ignore.case = TRUE uses a 256-entry byte-folding table without lowercasing each input string.

fgrepl(pattern, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE,
       useBytes = FALSE, nthreads = NULL)
Argument Description
pattern Character scalar. Pattern to search for.
x Character vector. NA elements return NA.
ignore.case Logical. Case-insensitive matching.
perl Logical. Use PCRE semantics instead of base R’s default (TRE) rules.
fixed Logical. Treat pattern as a literal string and use the prepared literal-search path.
useBytes Logical. Match byte by byte rather than by UTF-8 character, as in base R.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: logical vector the same length as x.

fgrepl("^inv", c("invoice", "Invoice", "credit"), ignore.case = TRUE)
[1]  TRUE  TRUE FALSE
fgrepl("a.b", c("axb", "ab"), fixed = TRUE)  # literal "a.b" — no match for "axb"
[1] FALSE FALSE

fgrep()

Equivalent to base::grep(): wraps fgrepl() and returns indices or values.

fgrep(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE,
      fixed = FALSE, useBytes = FALSE, invert = FALSE, nthreads = NULL)
Argument Description
pattern, x, ignore.case, perl, fixed, useBytes, nthreads Same as fgrepl().
value Logical. Return matching elements instead of indices.
invert Logical. Return non-matching indices/values instead.

Returns: integer vector of indices, or a character vector when value = TRUE.

fgrep("^inv", c("invoice", "credit", "invoice2"))
[1] 1 3
fgrep("^inv", c("invoice", "credit", "invoice2"), value = TRUE)
[1] "invoice"  "invoice2"

fcount()

No direct base R equivalent (the usual idiom is vapply(gregexpr(...), length, ...), which allocates a match-position vector per element just to take its length). Counts non-overlapping matches of one pattern in each element, using the same PCRE2 and prepared-fixed-string engines and the same parallel dispatch as fgrepl().

fcount(pattern, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE,
       useBytes = FALSE, nthreads = NULL)
Argument Description
pattern, x, ignore.case, perl, fixed, useBytes, nthreads Same as fgrepl().

Returns: integer vector the same length as x, with names(x) preserved. NA elements return NA; elements with no match return 0L.

An empty pattern, which has character-position semantics in base R, is delegated to base::gregexpr(). After an empty match the search moves on by one character, where gregexpr(perl = TRUE) moves on by one byte.

fcount("[0-9]", c("a1b2c3", "none", NA))
[1]  3  0 NA
fcount("aa", "aaaa", fixed = TRUE)   # 2 -- matches do not overlap
[1] 2
# Column-level data-quality rules, one vectorised call each
nm <- c("JOHN O'BRIEN", "UNKNOWN 00000000", "Kyle John Haynes")
fcount("[0-9]", nm)        # digits in a name field
[1] 0 8 0
fcount(" +", nm) + 1L      # token count
[1] 2 2 3

fsub()

Equivalent to base::sub(): first-match substitution. Supports \\1-\\9 capture groups and \\U/\\L/\\E case conversion in replacement.

fsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
     fixed = FALSE, useBytes = FALSE, nthreads = NULL)
Argument Description
pattern Character scalar. Pattern to search for.
replacement Character scalar. Replacement string.
x Character vector. NA elements return NA.
ignore.case, perl, fixed, useBytes, nthreads Same as fgrepl().

Returns: character vector the same length as x.

fsub("-([0-9]+)$", "_\\1", c("invoice-001", "invoice-002"))
[1] "invoice_001" "invoice_002"

fgsub()

Equivalent to base::gsub(): global substitution. Same capture-group and case-conversion support as fsub().

fgsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
      fixed = FALSE, useBytes = FALSE, nthreads = NULL)

Arguments are identical to fsub(). Returns: character vector the same length as x.

fgsub("[aeiou]", "_", c("hello world", "fast string"), ignore.case = TRUE)
[1] "h_ll_ w_rld" "f_st str_ng"

gsub_all()

No base R equivalent: applies several patterns in a single function call, either sequentially (chained, like repeated fgsub() calls — later patterns can match text introduced by earlier replacements) or, for fixed = TRUE, as one combined left-to-right scan (sequential = FALSE). Non-sequential regex replacement is rejected explicitly.

gsub_all(patterns, replacements, x, fixed = FALSE, ignore.case = FALSE,
         sequential = TRUE, nthreads = NULL, perl = FALSE, useBytes = FALSE)
Argument Description
patterns Character vector of patterns to search for.
replacements Character scalar or vector the same length as patterns.
x Character vector. NA elements return NA.
fixed Logical. Treat each pattern as a literal string.
ignore.case Logical. Case-insensitive matching.
sequential Logical (default TRUE). TRUE = chained passes; FALSE = fixed-pattern single combined scan.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.
perl Logical. As in fgsub().
useBytes Logical. As in fgsub().

Returns: character vector the same length as x.

gsub_all(c("Mr\\.", "Mrs\\."), c("Mister", "Missus"), c("Mr. Smith", "Mrs. Jones"))
[1] "Mister Smith" "Missus Jones"

fextract() / fextract_all()

The first match (or a capture group of it), or every non-overlapping match, as regmatches(x, regexpr(...)) / regmatches(x, gregexpr(...)) or stringr::str_extract() / str_extract_all() would return it. Patterns follow fgrepl()’s rules; after an empty match the search moves on one character, as in fcount().

fextract(pattern, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE,
         useBytes = FALSE, group = 0L, nthreads = NULL)
fextract_all(pattern, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE,
             useBytes = FALSE, group = 0L, nthreads = NULL)
Argument Description
pattern, x, ignore.case, perl, fixed, useBytes As in fgrepl().
group 0 for the whole match, k for capture group k (NA when the group did not take part). Must be 0 with fixed = TRUE.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: fextract() a character vector (NA for no match); fextract_all() a list of character vectors (character(0) for no match, NA for a missing string). Both keep names(x).

x <- c("Unit 4, 12 Smith St", "PO Box 99", NA)
fextract("[0-9]+", x)
[1] "4"  "99" NA  
fextract_all("[0-9]+", x)
[[1]]
[1] "4"  "12"

[[2]]
[1] "99"

[[3]]
[1] NA
fextract("([0-9]+) ([A-Za-z]+) St", x, group = 2)
[1] "Smith" NA      NA     

fgrepl_any() / fcount_any() / fwhich_any() / fextract_any()

Searches for any of many literal strings in one pass with an Aho-Corasick automaton, so thousands of keywords cost about as much as a few. Matches are leftmost-first: the earliest match wins, and among matches at the same position the pattern listed first. fwhich_any() returns the first pattern (in the order of patterns) found anywhere in the string, which suits priority-ordered keyword categories.

fgrepl_any(patterns, x, ignore.case = FALSE, useBytes = FALSE, nthreads = NULL)
fcount_any(patterns, x, ignore.case = FALSE, useBytes = FALSE, nthreads = NULL)
fwhich_any(patterns, x, ignore.case = FALSE, useBytes = FALSE, nthreads = NULL)
fextract_any(patterns, x, all = FALSE, ignore.case = FALSE, useBytes = FALSE,
             nthreads = NULL)
Argument Description
patterns Literal strings to look for (no NA or "").
x Character vector. NA elements return NA.
ignore.case Fold ASCII letters, as fgrepl(fixed = TRUE) does.
useBytes Match bytes rather than UTF-8 text.
all fextract_any(): return every match (a list).
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: a logical vector, integer vectors, or the matched text (a list with all = TRUE), the same length as x.

gsub_all(fixed = TRUE, sequential = FALSE) uses the same automaton once there are eight or more patterns.

notes <- c("stolen bicycle", "break and enter, tools taken", "graffiti", NA)
keywords <- c("stolen", "taken", "break and enter", "graffiti")
fgrepl_any(keywords, notes)
[1] TRUE TRUE TRUE   NA
fwhich_any(keywords, notes)
[1]  1  2  4 NA
fextract_any(keywords, notes, all = TRUE)
[[1]]
[1] "stolen"

[[2]]
[1] "break and enter" "taken"          

[[3]]
[1] "graffiti"

[[4]]
[1] NA

fagrepl() / fagrep()

Equivalents of agrepl() and agrep(): does each string contain something within max.distance edits of a literal pattern? Uses Myers’ bit-parallel algorithm. A max.distance below 1 is a fraction of the pattern length, rounded up, as in base R. Regular-expression patterns, custom costs and per-operation limits are passed to base R.

fagrepl(pattern, x, max.distance = 0.1, costs = NULL, ignore.case = FALSE,
        fixed = TRUE, useBytes = FALSE, nthreads = NULL)
fagrep(pattern, x, max.distance = 0.1, costs = NULL, ignore.case = FALSE,
       value = FALSE, fixed = TRUE, useBytes = FALSE, nthreads = NULL)

Returns: fagrepl() a logical vector (NA for NA input, where base R gives FALSE); fagrep() indices, or the matching elements with value = TRUE.

x <- c("1 lazy 2", "1 lasy 2", "1 LAZY 2", NA)
fagrepl("lasy", x)
[1]  TRUE  TRUE FALSE    NA
fagrepl("lasy", x, ignore.case = TRUE)
[1] TRUE TRUE TRUE   NA
fagrep("lasy", x, value = TRUE)
[1] "1 lazy 2" "1 lasy 2"

13.2 String utilities

The four base R equivalents (ftrimws(), fsubstr(), fnchar(), fchartr()) preserve names(x) and NA handling exactly like base R; the others keep names too.

ftrimws()

ftrimws(x, which = c("both", "left", "right"), whitespace = "[ \t\r\n]")
Argument Description
x Character vector. NA elements return NA.
which One of "both", "left", "right".
whitespace Regex of characters to strip. Only the default "[ \t\r\n]" uses the fast path; any other value delegates to base::trimws().

Returns: character vector the same length as x, with names(x) preserved.

ftrimws(c("  padded  ", "\ttabbed\n"))
[1] "padded" "tabbed"
ftrimws("  left only", which = "left")
[1] "left only"

fsubstr()

fsubstr(x, start, stop, nthreads = NULL)
Argument Description
x Character vector. NA elements return NA.
start, stop Integer (or numeric) vectors of length 1 or length(x), 1-indexed, clamped to each string’s bounds, recycled to length(x). NA in either produces NA for that element.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: character vector the same length as x.

fsubstr("NSWREC123456789", 1, 3)
[1] "NSW"
fsubstr(rep("ABCDEFGH", 3), c(1, 4, 7), c(3, 6, 8))  # vectorised start/stop
[1] "ABC" "DEF" "GH" 

fnchar()

fnchar(x, type = "chars", allowNA = FALSE, keepNA = NA, nthreads = NULL)
Argument Description
x Vector, coerced to character via as.character() if needed.
type One of "bytes", "chars", or "width". "width" delegates to base::nchar() (display width isn’t parallelised).
allowNA Logical. Ignored; the fast path never raises an encoding error regardless.
keepNA Logical or NA (default). NA/TRUE: NA elements of x return NA. FALSE: they return 2L (length of the string "NA"), matching base R’s legacy behaviour.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: integer vector the same length as x, with names(x) preserved.

fnchar(c("café", "abc", NA))
[1]  4  3 NA
fnchar(c("café", "abc"), type = "bytes")  # "é" is 2 bytes in UTF-8
[1] 5 3

fchartr()

fchartr(old, new, x, nthreads = NULL)
Argument Description
old, new Single strings with the same number of characters. Each character of old maps to the corresponding character of new.
x Character vector. NA elements return NA.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: character vector the same length as x. Falls back to base::chartr() automatically when old/new contain multi-byte characters (the fast path is a flat byte lookup table, valid only for single-byte/ASCII characters).

fchartr("'-", "  ", c("O'Brien", "Smith-Jones"))
[1] "O Brien"     "Smith Jones"
fchartr("aeiou", "AEIOU", "fast string")
[1] "fAst strIng"

fsquish()

Trims both ends and collapses internal runs of whitespace to one space, like stringr::str_squish(). Whitespace is Unicode’s White_Space set (including the no-break space and the ideographic space).

fsquish(x, nthreads = NULL)
fsquish(c("  12   Smith\tSt  ", "already clean", NA))
[1] "12 Smith St"   "already clean" NA             

fupper() / flower()

Upper- and lower-case text in parallel, with the full Unicode mappings ICU applies in its root locale, so one character can become several ("ß" to "SS") and a capital sigma lower-cases to the final form at the end of a word. base::toupper() and base::tolower() are single-threaded, map one character to exactly one character, and follow the session’s locale; these do not.

fupper(x, nthreads = NULL)
flower(x, nthreads = NULL)
fupper(c("Smith", "o'brien", "straße"))
[1] "SMITH"   "O'BRIEN" "STRASSE"
flower(c("MACDONALD", "ΟΔΟΣ"))
[1] "macdonald" "οδος"     
toupper("Straße")   # base R leaves the sharp s alone
[1] "STRAßE"

ftitle_case()

One capital per word, with the rules written names follow: a letter after "Mc" or after a one-letter prefix and an apostrophe is capitalised, nobiliary particles between two words stay in lower case, and an unambiguous Roman numeral suffix is upper-cased. style = "simple" turns all three off. Base R has no title-case function.

ftitle_case(x, style = c("name", "simple"), particles = NULL, nthreads = NULL)
x <- c("MARY-JANE O'BRIEN", "mcdonald", "vincent van gogh",
       "van gogh, vincent", "john smith iii", "3rd street")
data.frame(x, name = ftitle_case(x), simple = ftitle_case(x, "simple"))
                  x              name            simple
1 MARY-JANE O'BRIEN Mary-Jane O'Brien Mary-Jane O'brien
2          mcdonald          McDonald          Mcdonald
3  vincent van gogh  Vincent van Gogh  Vincent Van Gogh
4 van gogh, vincent Van Gogh, Vincent Van Gogh, Vincent
5    john smith iii    John Smith III    John Smith Iii
6        3rd street        3rd Street        3rd Street

fstrsplit()

Every field of each string, cut where base::strsplit() cuts them, with the separator search parallelised. simplify = TRUE gives an NA-padded character matrix instead of a list, which is what do.call(rbind, ...) would build but without the copying. The search is the only parallel part, so a literal one-character separator (where base R is already at the floor of creating the result strings) is no faster here; a regular expression is about twice as fast, and simplify = TRUE about four times.

fstrsplit(x, split, simplify = FALSE, fixed = FALSE, perl = FALSE,
          ignore.case = FALSE, useBytes = FALSE, nthreads = NULL)
x <- c("12 Smith St", "4/7 Bay Rd", NA)
fstrsplit(x, " ", fixed = TRUE)
[[1]]
[1] "12"    "Smith" "St"   

[[2]]
[1] "4/7" "Bay" "Rd" 

[[3]]
[1] NA
fstrsplit(x, " ", fixed = TRUE, simplify = TRUE)
     [,1]  [,2]    [,3]
[1,] "12"  "Smith" "St"
[2,] "4/7" "Bay"   "Rd"
[3,] NA    NA      NA  
fstrsplit("a  b   c", "\\s+")
[[1]]
[1] "a" "b" "c"

fsplit_field()

One field of each string split at split, like stringr::str_split_i() or DuckDB’s split_part(), without building the intermediate list. Every field counts, including empty ones.

fsplit_field(x, split, field, fixed = FALSE, perl = FALSE,
             ignore.case = FALSE, useBytes = FALSE, nthreads = NULL)
Argument Description
split The separator: a regular expression unless fixed = TRUE; must not match "".
field Non-zero integer; negative values count from the end (-1 is the last field).

Returns: character vector, NA where the string has fewer fields.

x <- c("2024-03-15", "1999-12-31", "bad", NA)
fsplit_field(x, "-", 1, fixed = TRUE)
[1] "2024" "1999" "bad"  NA    
fsplit_field(x, "-", -1, fixed = TRUE)
[1] "15"  "31"  "bad" NA   

ascii_fold()

ICU’s "Latin-ASCII" transliteration (stringi::stri_trans_general(x, "Latin-ASCII")) from a built-in table: accents removed, ligatures and special letters spelled out, typographic punctuation and spaces made ASCII. Characters it cannot fold are kept, or replaced by sub.

ascii_fold(x, sub = NULL, nthreads = NULL)
ascii_fold(c("François Müller", "Æsir Ørsted", "Straße"))
[1] "Francois Muller" "AEsir Orsted"    "Strasse"        
ascii_fold("Δι café", sub = "")
[1] " cafe"

fpad()

Pads each string to at least width characters, like stringr::str_pad(). Width counts characters (code points), so accented text pads correctly.

fpad(x, width, side = c("left", "right", "both"), pad = " ", nthreads = NULL)
Argument Description
side "left" (right-aligns the text), "right" or "both" (the left gets the smaller half).
pad A single character.
fpad(c("800", "4000", "2", NA), 4, pad = "0")
[1] "0800" "4000" "0002" NA    
fpad("abc", 7, side = "both", pad = "*")
[1] "**abc**"

freplace_tokens()

Splits each string at whitespace, replaces every token found in from with the matching element of to ("" deletes it) and joins the tokens with single spaces. Only whole tokens are replaced; replacements are not re-scanned. See sec-uc-clean for dictionaries of abbreviations and nicknames.

freplace_tokens(x, from, to, ignore_case = FALSE, nthreads = NULL)
Argument Description
from Tokens to replace: non-empty, no whitespace; the first of any duplicates wins.
to Replacements, the same length as from or length 1.
ignore_case Match regardless of the case of ASCII letters.

Returns: character vector; the result is squished even where nothing is replaced.

freplace_tokens(c("12 SMITH ST", "  7   KING   ST  "), c("ST", "RD"),
                c("STREET", "ROAD"))
[1] "12 SMITH STREET" "7 KING STREET"  
freplace_tokens("Dr John Smith", c("dr", "mr"), "", ignore_case = TRUE)
[1] "John Smith"

url_encode() / url_decode()

Percent-encoding as utils::URLencode() and decoding as utils::URLdecode(), over whole vectors in parallel. url_decode() keeps a broken escape such as %zz as it is, and with plus = TRUE decodes + as a space.

url_encode(x, reserved = FALSE, repeated = FALSE, nthreads = NULL)
url_decode(x, plus = FALSE, nthreads = NULL)
Argument Description
reserved Also encode the reserved characters (for one URL component).
repeated Encode strings that already contain %xx escapes (URLencode() returns them unchanged).
plus Decode + as a space, as form data and query strings use it.
enc <- url_encode(c("fish & chips", "caf\u00e9 /menu"), reserved = TRUE)
enc
[1] "fish%20%26%20chips"  "caf%C3%A9%20%2Fmenu"
url_decode(enc)
[1] "fish & chips" "café /menu"  
url_decode("q=meat+pie%21", plus = TRUE)
[1] "q=meat pie!"

html_unescape() / html_escape()

Decodes HTML character references exactly as Python’s html.unescape(): all 2,231 named references of the HTML standard (including legacy ones without a semicolon) and decimal and hexadecimal numeric references, with the standard’s rules for invalid numbers. html_escape() is the other direction, escaping what htmltools::htmlEscape() escapes: &, < and >, plus the quotes and line breaks with attribute = TRUE.

html_unescape(x, nthreads = NULL)
html_escape(x, attribute = FALSE, nthreads = NULL)
html_unescape(c("Fish &amp; Chips", "caf&eacute; &#8211; open", "AT&T"))
[1] "Fish & Chips" "café – open"  "AT&T"        
html_escape(c("Fish & Chips", "<b>bold</b>"))
[1] "Fish &amp; Chips"        "&lt;b&gt;bold&lt;/b&gt;"
html_escape('say "hi"', attribute = TRUE)
[1] "say &quot;hi&quot;"

13.3 Clustering keys

fingerprint() / ngram_fingerprint()

OpenRefine’s key-collision keys for grouping spelling variants. The fingerprint lowercases, decomposes and strips accents and punctuation, then sorts and de-duplicates the words; the n-gram fingerprint removes all whitespace and keeps the sorted, de-duplicated character n-grams.

fingerprint(x, nthreads = NULL)
ngram_fingerprint(x, n = 2L, nthreads = NULL)
x <- c("Smith, John", "john SMITH", "John  Smith.", "Jon Smith")
fingerprint(x)
[1] "john smith" "john smith" "john smith" "jon smith" 
ngram_fingerprint(c("Acme Pty Ltd", "ACME PtyLtd"))
[1] "accmepltmepttdtyyl" "accmepltmepttdtyyl"

13.4 Parsing, validation and hashing

fparse_number()

The first number in each string, ignoring currency symbols, units, labels and grouping marks, like readr::parse_number(). A minus sign counts even with a currency symbol or space between it and the digits, but not when it joins two words ("SKU-123" is 123). The value is the correctly rounded double, as as.numeric() would give for the number found.

fparse_number(x, decimal_mark = ".", grouping_mark = ",", nthreads = NULL)
Argument Description
decimal_mark A single character.
grouping_mark Characters allowed between digit groups ("" for none).

Returns: double vector, NA where a string holds no number.

fparse_number(c("$1,234.50", "12.5%", "approx. 3,000 kg", "-$45", "n/a"))
[1] 1234.5   12.5 3000.0  -45.0     NA
fparse_number("1.234,50 EUR", decimal_mark = ",", grouping_mark = ".")
[1] 1234.5

valid_id()

Whether each string is a well-formed identifier of the given type: right length, right characters and a correct check digit, ignoring spaces and hyphens. Types: "luhn" (payment cards, IMEIs, …), "abn", "acn", "tfn" (9 digits; 8-digit TFNs give NA), "medicare", "isbn" (10 or 13), "ean" (EAN-8, UPC-A, EAN-13, GTIN-14) and "iban". Apart from Medicare, the rules are tested against python-stdnum.

valid_id(x, type = c("luhn", "abn", "acn", "tfn", "medicare", "isbn", "ean", "iban"),
         nthreads = NULL)
valid_id(c("51 824 753 556", "51 824 753 557"), "abn")
[1]  TRUE FALSE
valid_id(c("4111 1111 1111 1111", "4111 1111 1111 1112"), "luhn")
[1]  TRUE FALSE
valid_id("GB82 WEST 1234 5698 7654 32", "iban")
[1] TRUE

string_shape()

Each string’s pattern of character classes – A for an upper-case letter, a for a lower-case one, 9 for a digit, everything else kept – for profiling the formats in a column (sec-uc-profile). Classes follow Unicode categories; combining marks are dropped.

string_shape(x, collapse = FALSE, ignore_case = FALSE, nthreads = NULL)
Argument Description
collapse Collapse each run of A, a or 9 to one character.
ignore_case Map every letter to a.
string_shape(c("0412 345 678", "(07) 3123 4567", "QLD 4000", "O'Brien"))
[1] "9999 999 999"   "(99) 9999 9999" "AAA 9999"       "A'Aaaaa"       
string_shape(c("0412 345 678", "O'Brien"), collapse = TRUE)
[1] "9 9 9" "A'Aa" 

fhash()

A lower-case hex digest of each string’s UTF-8 bytes: SHA-256 (default), SHA-1, MD5, SHA-512 or the non-cryptographic XXH64. With a key, the SHA and MD5 digests become HMACs, the standard keyed pseudonym (sec-uc-privacy). Digests agree with openssl and digest.

fhash(x, algo = c("sha256", "sha1", "md5", "sha512", "xxh64"), key = NULL,
      seed = 0, nthreads = NULL)
Argument Description
key Secret for an HMAC: a string or a raw vector. Not allowed with "xxh64".
seed Seed for "xxh64".
fhash("abc")
[1] "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
fhash("abc", "md5")
[1] "900150983cd24fb0d6963f7d28e17f72"
fhash("123456782", key = "secret")
[1] "73e89fd22fe7409a215ceb7a71b1eee7c44f09b6f14cedfb7a3c6a4273236182"
fhash("abc", "xxh64")
[1] "44bc2cf5ad770999"

13.5 Dates

format_date()

format_date(x, format = c("iso", "compact", "dmy", "ymd_slash"),
            nthreads = NULL)
Argument Description
x A Date object or numeric vector of days since 1970-01-01.
format "iso" (YYYY-MM-DD), "compact" (YYYYMMDD), "dmy" (DD/MM/YYYY), or "ymd_slash" (YYYY/MM/DD).
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: character vector the same length as x.

format_date(as.Date(c("2024-06-18", NA)), "compact")
[1] "20240618" NA        

format_date_parts()

Pure string-building (zero-padding plus punctuation, no calendar math, no Date object) — the inverse of date_parts().

format_date_parts(year, month, day,
                  format = c("iso", "compact", "dmy", "ymd_slash"),
                  nthreads = NULL)
Argument Description
year, month, day Numeric vectors, recycled to a common length. NA, non-integer-coercible, or out-of-width values (year outside 0-9999, month/day outside 0-99) produce NA for that element. No calendar validation — month = 13 formats as given if it fits the field width.
format Same four options as format_date().
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: character vector recycled to the common length of year, month, day.

format_date_parts(2024, 6, 18, "iso")
[1] "2024-06-18"

date_parts()

date_parts(x, nthreads = NULL)
Argument Description
x A Date object or numeric vector of days since 1970-01-01.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: a data.frame with integer columns year, month, day.

date_parts(as.Date(c("2024-06-18", "1999-12-31")))
  year month day
1 2024     6  18
2 1999    12  31

fas.Date()

Reads one fixed format (no locale handling or format guessing) and checks the full calendar, so impossible dates are NA as with base::as.Date(). Numeric x is read as counts from a standard epoch (Excel, SAS/Stata, SPSS, MATLAB, Julian days, …); see ?fas.Date for the table.

fas.Date(x, format = c("iso", "compact", "dmy", "ymd_slash"),
         origin = "unix", nthreads = NULL)
Argument Description
x Character vector, or numeric counts from origin. Character elements that don’t match format exactly (wrong length/separators/non-digits) or are not a real calendar date become NA. A Date is returned as is; a date-time is converted with base::as.Date().
format Same four options as format_date(); x must be in exactly this one format.
origin For numeric x: a named epoch ("unix", "excel", "sas", …) or a day 0 as a Date or "YYYY-MM-DD" string.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: a Date vector the same length as x.

fas.Date(c("18/06/2024", "29/02/2023", "not-a-date"), "dmy")
[1] "2024-06-18" NA           NA          
fas.Date(c(1, 60, 45000), origin = "excel")
[1] "1900-01-01" NA           "2023-03-15"

fas.POSIXct()

Parses strict, locale-free timestamps directly into UTC seconds since the Unix epoch — no timezone-database consultation, no multi-format guessing. Unlike fas.Date(), calendar dates are fully validated, including month lengths and leap years.

fas.POSIXct(x, format = c("iso", "rfc3339", "compact", "iso_offset"),
            nthreads = NULL)
Argument Description
x Character vector. NA elements, malformed values, and out-of-range or impossible calendar dates become NA.
format "iso" (YYYY-MM-DD HH:MM:SS), "rfc3339" (YYYY-MM-DDTHH:MM:SSZ), "compact" (YYYYMMDDHHMMSS), or "iso_offset" (YYYY-MM-DDTHH:MM:SS+HH:MM).
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: a POSIXct vector in UTC, the same length as x, with names(x) preserved.

fas.POSIXct(c("2024-06-18 09:15:00", "not a time"))
[1] "2024-06-18 09:15:00 UTC" NA                       
fas.POSIXct("2024-06-18T09:15:00Z", "rfc3339")
[1] "2024-06-18 09:15:00 UTC"
fas.POSIXct("20240618091500", "compact")
[1] "2024-06-18 09:15:00 UTC"
fas.POSIXct("2024-06-18T09:15:00+10:00", "iso_offset")  # normalised to UTC
[1] "2024-06-17 23:15:00 UTC"
fas.POSIXct("2023-02-29 08:00:00")                      # NA -- not a leap year
[1] NA

format_datetime()

The inverse: formats Unix-epoch seconds without locale or timezone-database overhead.

format_datetime(x, format = c("iso", "rfc3339", "compact", "iso_offset"),
                offset = "Z", nthreads = NULL)
Argument Description
x A POSIXct object or numeric vector of seconds since 1970-01-01 00:00:00 UTC.
format The same four formats accepted by fas.POSIXct().
offset Fixed offset written by format = "iso_offset": "Z", or a signed "+HH:MM"/"-HH:MM" string. Must be "Z" for the other three formats, which are emitted in UTC.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: character vector the same length as x.

"iso_offset" applies one fixed numeric offset to every element. It is not a timezone — there are no daylight-saving rules — so use base::format() with a real timezone when a series crosses a DST boundary.

stamps <- fas.POSIXct(c("2024-06-18 09:15:00", "2024-06-18 23:59:59"))
format_datetime(stamps, "rfc3339")
[1] "2024-06-18T09:15:00Z" "2024-06-18T23:59:59Z"
format_datetime(stamps, "compact")
[1] "20240618091500" "20240618235959"
format_datetime(stamps, "iso_offset", offset = "+10:00")
[1] "2024-06-18T19:15:00+10:00" "2024-06-19T09:59:59+10:00"

13.6 Phonetic blocking keys

None of these functions has a base R equivalent; all are intended as blocking keys ahead of fuzzy name matching (sec-theory, sec-workflow).

soundex()

soundex(x, nthreads = NULL)
Argument Description
x Character vector (coerced via as.character() if not already character — e.g. a factor read from CSV). NA elements, and elements with no alphabetic characters, return NA.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: character vector the same length as x, with names(x) preserved; each element either NA or exactly 4 characters.

soundex(c("Robert", "Rupert", "Ashcraft"))
[1] "R163" "R163" "A261"

nysiis()

nysiis(x, nthreads = NULL)
Argument Description
x Character vector (coerced via as.character() if needed). NA elements, and elements with no alphabetic characters, return NA.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: character vector the same length as x, with names(x) preserved; each element either NA or up to 6 characters.

nysiis(c("Robert", "Rupert", "Ashcraft"))
[1] "RABAD"  "RAPAD"  "ASCRAF"

refined_soundex()

The US-English Refined Soundex mapping from Apache Commons Codec. Where classic soundex() discards vowels and truncates to four characters, Refined Soundex encodes vowels too and emits a code for every change in phonetic class, with no truncation — a longer, more discriminating key that produces smaller blocks.

refined_soundex(x, nthreads = NULL)
Argument Description
x Character vector (coerced via as.character() if needed). NA elements, and elements with no ASCII letters, return NA.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: character vector the same length as x, with names(x) preserved. Code length varies with the input and is not truncated — note that phonics::refinedSoundex() caps codes at 10 characters by default, so the two agree only once its maxCodeLen is raised (sec-theory).

refined_soundex(c("Robert", "Rupert", "Ashcraft"))
[1] "R901096"   "R901096"   "A03039026"
# Splits a Soundex block that classic soundex() merges
data.frame(
    name    = c("Smith", "Smyth", "Schmidt", "Sandy"),
    soundex = soundex(c("Smith", "Smyth", "Schmidt", "Sandy")),
    refined = refined_soundex(c("Smith", "Smyth", "Schmidt", "Sandy"))
)
     name soundex refined
1   Smith    S530  S38060
2   Smyth    S530  S38060
3 Schmidt    S530  S30806
4   Sandy    S530  S30860

cologne()

The Cologne phonetic algorithm (Kölner Phonetik), designed for German pronunciation. Input is uppercased bytewise, umlauts are mapped to their base vowels, sharp s to SS, and remaining non-letters ignored before encoding — so German spelling variants that ASCII-only schemes split are grouped together.

cologne(x, nthreads = NULL)
Argument Description
x Character vector (coerced via as.character() if needed). NA elements, and elements with no supported letters, return NA.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: character vector the same length as x, with names(x) preserved; a digit string, or NA.

cologne(c("Müller-Lüdenscheidt", "Meier", "Meyer"))
[1] "65752682" "67"       "67"      
# Umlaut folding: refined_soundex() splits this pair, cologne() doesn't
data.frame(
    name    = c("Müller", "Mueller"),
    refined = refined_soundex(c("Müller", "Mueller")),
    cologne = cologne(c("Müller", "Mueller"))
)
     name refined cologne
1  Müller  M80709     657
2 Mueller  M80709     657

double_metaphone()

Two codes per word — primary and secondary — for ambiguous pronunciations. Ported from the structure of Apache Commons Codec’s Java implementation and cross-checked against its published test vectors. Unlike soundex()/nysiis(), internal whitespace/punctuation is not stripped before encoding (only the ends are trimmed and the text uppercased) — the algorithm itself keys off literal fragments like "VAN "/"SCH", including the space.

double_metaphone(x, nthreads = NULL)
Argument Description
x Character vector (coerced via as.character() if needed). NA elements, and elements with no content after trimming, return NA in both columns.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: a data.frame with character columns primary and secondary, each length(x) long.

double_metaphone(c("Smith", "Schmidt", "Catherine", "Kathryn"))
  primary secondary
1     SM0       XMT
2     XMT       SMT
3    K0RN      KTRN
4    K0RN      KTRN

caverphone()

Caverphone 2.0 (Caversham Project, University of Otago) — a fixed 10-character code via a chain of substring transforms, widely used in NZ/AU record linkage. Ported step-for-step from Apache Commons Codec’s Caverphone2 and cross-checked against its published test vectors, including the “enough”/“trough” duplicate-rule quirk inherited from the original 2004 specification (preserved rather than “corrected” — the point of a phonetic key is to match the standard everyone else uses).

caverphone(x, nthreads = NULL)
Argument Description
x Character vector (coerced via as.character() if needed). NA elements return NA; every other input — including "" — returns a 10-character code.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: character vector the same length as x, with names(x) preserved; each element either NA or exactly 10 characters.

caverphone(c("Peter", "Tedder", "Stevenson"))
[1] "PTA1111111" "TTA1111111" "STFNSN1111"

metaphone()

Lawrence Philips’ original Metaphone, as Apache Commons Codec implements it (which Solr and Elasticsearch use). phonics::metaphone() follows PHP’s variant instead.

metaphone(x, max_length = 4L, nthreads = NULL)
metaphone(c("Thompson", "Knight", "Wright", "Christopher"))
[1] "0MPS" "NT"   "RT"   "XRST"

mra_encode() / mra_compare()

The Western Airlines Match Rating Approach (1977): a codex of at most six letters, and a pairwise match test, following the published rules as the Python jellyfish package implements them.

mra_encode(x, nthreads = NULL)
mra_compare(a, b, nthreads = NULL)
mra_encode(c("Byrne", "Boern", "Catherine", "Kathryn"))
[1] "BYRN"   "BRN"    "CTHRN"  "KTHRYN"
mra_compare(c("Byrne", "Michael"), c("Boern", "Mike"))
[1]  TRUE FALSE

statcan(), lein(), phonex(), roger_root(), onca()

Five more name codes from the record-linkage literature. The first four reproduce the phonics package rule for rule (but ignore non-letters instead of returning NA, and fold accents); onca() is NYSIIS followed by Soundex.

statcan(x, max_length = 4L, nthreads = NULL)
lein(x, max_length = 4L, nthreads = NULL)
phonex(x, max_length = 4L, nthreads = NULL)
roger_root(x, max_length = 5L, nthreads = NULL)
onca(x, max_length = 4L, nthreads = NULL)
x <- c("William", "Peter", "Stevenson", "Stephenson")
data.frame(x, statcan = statcan(x), lein = lein(x), phonex = phonex(x),
           roger_root = roger_root(x), onca = onca(x))
           x statcan lein phonex roger_root onca
1    William     WLM W320   W450      45300 W450
2      Peter     PTR P130   B360      09140 P360
3  Stevenson    STVN S142   S315      00182 S315
4 Stephenson    STPH S142   S315      00182 S315

daitch_mokotoff()

The Daitch-Mokotoff Soundex, six digits from whole letter sequences ("SCH", "SZCZ", "RZ") rather than single consonants, for the Slavic and Germanic spellings American Soundex separates. A spelling that could be said more than one way gets a code for each reading, which simplify = TRUE returns as a matrix: one blocking pass per column. The coding rules are Apache Commons Codec’s, and the codes match that implementation, except that a value with no letter to code is NA here rather than 000000.

daitch_mokotoff(x, simplify = FALSE, nthreads = NULL)
daitch_mokotoff(c("Moskowitz", "Moskovitz"))
[[1]]
[1] "645740"

[[2]]
[1] "645740"
daitch_mokotoff(c("Auerbach", "Ohrbach"))   # two readings of "ch"
[[1]]
[1] "097400" "097500"

[[2]]
[1] "097400" "097500"
daitch_mokotoff(c("Peters", "Waszkiewicz"), simplify = TRUE)
     [,1]     [,2]    
[1,] "734000" "739400"
[2,] "745740" NA      

13.7 Fuzzy string similarity

jaro_winkler()

Vectorised pairwise Jaro-Winkler similarity. See sec-theory for the algorithm and the bit-parallel implementation.

jaro_winkler(a, b, p = 0.1, nthreads = NULL, use_bytes = TRUE)
Argument Description
a, b Equal-length character vectors.
p Prefix scaling factor (default 0.1, the standard value).
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.
use_bytes TRUE for compatibility byte comparison; FALSE for UTF-8 code points.

Returns: numeric vector of similarities in [0, 1].

jaro_winkler(c("MARTHA", "DWAYNE"), c("MARHTA", "DUANE"))
[1] 0.9611111 0.8400000
jaro_winkler("SMITH", "SMYTH", p = 0)    # no prefix bonus
[1] 0.8666667
jaro_winkler("SMITH", "SMYTH", p = 0.1)  # standard prefix bonus
[1] 0.8933333

jaro_winkler_matrix()

All-pairs Jaro-Winkler similarity — every element of a against every element of b.

jaro_winkler_matrix(a, b, p = 0.1, nthreads = NULL, use_bytes = TRUE)
Argument Description
a Character vector of length n (rows).
b Character vector of length m (columns).
p, nthreads Same as jaro_winkler().
use_bytes Logical. Compare encoded bytes (TRUE) or UTF-8 code points (FALSE).

Returns: numeric matrix of dimensions n × m.

jaro_winkler_matrix(c("JOHN SMITH", "MARY JONES"), c("JON SMYTH", "MARY JONES", "JOHN SMITH"))
          [,1]      [,2]      [,3]
[1,] 0.9170370 0.4222222 1.0000000
[2,] 0.3074074 1.0000000 0.4222222

jaro_winkler_tokens()

Token-reorder- and punctuation-aware Jaro-Winkler similarity. Full mechanics in sec-theory.

jaro_winkler_tokens(a, b, p = 0.1, ignore_case = FALSE, strip = "['’-]",
                    extra_penalty = NULL, contractions = FALSE,
                    nthreads = NULL)
Argument Description
a, b Equal-length character vectors.
p Prefix scaling factor (default 0.1).
ignore_case Logical (default FALSE). Uppercase both sides before comparing.
strip Single regex string matching punctuation to remove before tokenising, or NULL to skip. Default "['’-]" strips straight/curly apostrophes and hyphens.
extra_penalty NULL (default) or a non-negative numeric scalar. NULL: unmatched tokens dilute the average (divide by max(n_tokens_a, n_tokens_b)). A number: average over only matched tokens, then subtract extra_penalty per unmatched token (floored at 0) — 0 ignores extra tokens outright.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: numeric vector of similarities in [0, 1]. NA if either side of a pair is NA.

# Reordered tokens, one near-miss — rescued relative to plain jaro_winkler()
jaro_winkler_tokens("Kyle John Haynes", "John Kylie Haynes")
[1] 0.9844444
jaro_winkler("Kyle John Haynes", "John Kylie Haynes")
[1] 0.8970588
# Punctuation/spacing variants of the same name
jaro_winkler_tokens(c("OBrien", "OBrien"), c("O Brien", "O'Brien"))
[1] 1 1
# A stray extra token, penalised by default...
jaro_winkler_tokens("Kylie John ZZ Haynes", "Haynes John Kyle")
[1] 0.7383333
# ...vs. ignored outright with extra_penalty = 0
jaro_winkler_tokens("Kylie John ZZ Haynes", "Haynes John Kyle", extra_penalty = 0)
[1] 0.9844444
# ...vs. lightly discounted
jaro_winkler_tokens("Kylie John ZZ Haynes", "Haynes John Kyle", extra_penalty = 0.1)
[1] 0.8844444

13.8 Fuzzy lookup

fuzzy_match() returns the best table index for every query. fuzzy_top_n() returns a long data frame of ranked candidates. Both scan the table without allocating a full all-pairs matrix and compare UTF-8 code points by default.

fuzzy_match(x, table,
            method = c("jaro_winkler", "levenshtein", "osa", "damerau_levenshtein"),
            p = 0.1, min_score = 0, max_distance = NULL, match_na = FALSE,
            nomatch = NA_integer_, nthreads = NULL, use_bytes = FALSE)
fuzzy_top_n(x, table,
            method = c("jaro_winkler", "levenshtein", "osa", "damerau_levenshtein"),
            top_n = 5L, p = 0.1, min_score = 0, max_distance = NULL,
            match_na = FALSE, nthreads = NULL, use_bytes = FALSE)

Supported methods are "jaro_winkler", "levenshtein", "osa", and "damerau_levenshtein". Scores are normalized to [0, 1]; ties resolve to the earliest table position.

fuzzy_match(c("SMITH", "JONES"), c("SMYTH", "JONAS", "JONES"))
[1] 1 3
fuzzy_top_n("kitten", c("sitting", "mitten", "cat"),
            method = "levenshtein", top_n = 2)
  query_index table_index     score rank
1           1           2 0.8333333    1
2           1           1 0.5714286    2

fuzzy_within()

Every table entry within max_distance edits of each query, found with SymSpell’s symmetric-delete index instead of comparing every pair. Candidates are verified with the exact distance, so the result is exactly the set of pairs within the cutoff.

fuzzy_within(x, table, max_distance = 1L,
             method = c("osa", "levenshtein", "damerau_levenshtein"),
             prefix_length = 7L, nthreads = NULL, use_bytes = FALSE)

Returns: a data frame of query_index, table_index and distance.

fuzzy_within(c("SMITH", "JONSE"),
             c("SMITH", "SMYTH", "SMITHE", "SIMTH", "JONES", "SMITHS"))
  query_index table_index distance
1           1           1        0
2           1           2        1
3           1           3        1
4           1           4        1
5           1           6        1
6           2           5        1

tfidf_top_n() / tfidf_match()

Cosine similarity of TF-IDF weighted character n-grams, as ING’s sparse_dot_topn and string_grouper compute it, with the IDF learnt from table. An inverted index means each query only meets the entries it shares an n-gram with.

tfidf_top_n(x, table, top_n = 5L, q = 3L, min_score = 0, nthreads = NULL,
            use_bytes = FALSE)
tfidf_match(x, table, q = 3L, min_score = 0, nomatch = NA_integer_,
            nthreads = NULL, use_bytes = FALSE)
companies <- c("ACME PTY LTD", "ACME HOLDINGS PTY LTD", "APEX PTY LTD",
               "BETA INDUSTRIES PTY LTD")
tfidf_top_n(c("ACME LTD", "BETA IND"), companies, top_n = 2)
  query_index table_index     score rank
1           1           1 0.5501441    1
2           1           2 0.3221424    2
3           2           4 0.6075407    1

minhash_pairs()

Candidate pairs whose q-gram Jaccard similarity probably reaches threshold, by MinHash signatures and banded locality-sensitive hashing (as datasketch’s MinHashLSH and zoomerjoin). Bands and rows are chosen as datasketch does; with verify = TRUE every pair returned has an exact Jaccard similarity of at least threshold, and weights = c(0.1, 0.9) trades time for fewer missed pairs.

minhash_pairs(x, y = NULL, threshold = 0.5, q = 3L, n_hash = 128L,
              bands = NULL, weights = c(0.5, 0.5), seed = 1, verify = TRUE,
              nthreads = NULL, use_bytes = FALSE)
x <- c("12 SMITH STREET BRISBANE", "12 SMITH ST BRISBANE",
       "45 JONES ROAD IPSWICH", "45 JONES RD IPSWICH", "7 KING LANE")
minhash_pairs(x, threshold = 0.4)
  x_index y_index   jaccard
1       1       2 0.7391304
2       3       4 0.7142857

13.9 Blocking and clustering

block_pairs()

Every pair of records that agree exactly on at least one key. Each column of a data frame is one blocking pass; a pair found by several passes is reported once, with the first. NA keys never pair. With y, pairs link x to y; without it, pairs are within x (x_index < y_index).

block_pairs(x, y = NULL, max_block_size = Inf, nthreads = NULL)
Argument Description
x, y A key vector, or a data frame or list of keys (one per pass).
max_block_size Skip blocks with more records than this, with a warning.

Returns: data frame with x_index, y_index and pass.

people <- data.frame(surname = c("SMITH", "SMYTH", "JONES", "SMITH"),
                     dob = as.Date(c("1980-01-02", "1980-01-02", "1975-06-30",
                                     "1990-12-01")))
block_pairs(data.frame(soundex(people$surname), people$dob))
  x_index y_index pass
1       1       2    1
2       1       4    1
3       2       4    1

sorted_neighbourhood()

The sorted neighbourhood method: sorts the distinct key values and pairs records whose values are within (window - 1) / 2 places of each other (and records with equal values), as Python’s recordlinkage does. Several keys give several passes, as in block_pairs().

sorted_neighbourhood(x, y = NULL, window = 3L, nthreads = NULL)
surname <- c("SMITH", "SMITHE", "SMYTH", "JONES", "JONSON")
sorted_neighbourhood(surname, window = 3)
  x_index y_index pass
1       1       2    1
2       1       5    1
3       2       3    1
4       4       5    1

cluster_pairs()

Entity identifiers from matched pairs: records joined by any chain of pairs share a cluster (connected components, by union-find). Clusters are numbered in the order of their lowest-indexed record; records in no pair are clusters of their own.

cluster_pairs(i, j = NULL, n = NULL)
Argument Description
i, j The two record indices of each pair, or a data frame of pairs as i.
n Number of records (default: the largest index).
cluster_pairs(c(1, 2, 5), c(2, 4, 6))
[1] 1 1 2 1 3 3

13.10 Edit distance

The edit-distance family distinguishes OSA from unrestricted Damerau-Levenshtein and offers normalized and bounded forms. Byte comparison is the compatibility default; use_bytes = FALSE compares UTF-8 code points.

levenshtein()

levenshtein(a, b, nthreads = NULL, use_bytes = TRUE, weights = c(1, 1, 1))
Argument Description
a, b Equal-length character vectors.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.
use_bytes TRUE for encoded bytes; FALSE for UTF-8 code points.
weights Costs of an insertion, a deletion and a substitution (as RapidFuzz’s weights); also accepted by levenshtein_matrix() and levenshtein_similarity().

Returns: numeric vector the same length as a (minimum number of single-character insertions/deletions/substitutions). NA if either side of a pair is NA.

levenshtein("kitten", "sitting")
[1] 3

levenshtein_matrix()

All-pairs Levenshtein distance.

levenshtein_matrix(a, b, nthreads = NULL, use_bytes = TRUE)

Returns: numeric matrix of dimensions length(a) x length(b).

levenshtein_matrix(c("kitten", "cat"), c("sitting", "bat"))
     [,1] [,2]
[1,]    3    5
[2,]    6    1

osa_distance() / osa_distance_matrix()

Adjacent transpositions cost one edit under the Optimal String Alignment restriction that no substring is edited more than once.

osa_distance(a, b, nthreads = NULL, use_bytes = TRUE)
osa_distance_matrix(a, b, nthreads = NULL, use_bytes = TRUE)

Arguments identical to levenshtein(). Returns: numeric vector the same length as a.

osa_distance("ca", "abc")  # 3
[1] 3

damerau_levenshtein() / damerau_levenshtein_matrix()

Unrestricted Damerau-Levenshtein permits a substring to participate in multiple edits and matches stringdist(method = "dl").

damerau_levenshtein(a, b, nthreads = NULL, use_bytes = TRUE)
damerau_levenshtein_matrix(a, b, nthreads = NULL, use_bytes = TRUE)
damerau_levenshtein("ca", "abc")  # 2
[1] 2

Normalized and bounded edit comparison

levenshtein_similarity(), osa_similarity(), and damerau_levenshtein_similarity() return 1 - distance/max(lengths). levenshtein_within() uses a banded dynamic program to test a raw cutoff.

levenshtein_similarity(a, b, nthreads = NULL, use_bytes = TRUE)
levenshtein_within(a, b, max_distance, nthreads = NULL, use_bytes = TRUE)

hamming()

Number of positions at which two equal-length strings differ.

hamming(a, b, nthreads = NULL, use_bytes = TRUE)

Arguments identical to levenshtein(). Returns: numeric vector the same length as a; Inf for a pair of unequal length (matching stringdist::stringdist(method = "hamming")).

hamming("karolin", "kathrin")
[1] 3
hamming("abc", "ab")  # Inf -- unequal length
[1] Inf

edit_ops()

The edits that turn each a[i] into b[i], as RapidFuzz’s Levenshtein.editops() / opcodes() list them, choosing the same alignment when several are equally short. Positions are 1-based.

edit_ops(a, b, type = c("editops", "opcodes"), use_bytes = FALSE)
edit_ops("kitten", "sitting")
  pair    type a_pos b_pos
1    1 replace     1     1
2    1 replace     5     5
3    1  insert     7     7
edit_ops("kitten", "sitting", type = "opcodes")
  pair    type a_start a_end b_start b_end
1    1 replace       1     1       1     1
2    1   equal       2     4       2     4
3    1 replace       5     5       5     5
4    1   equal       6     6       6     6
5    1  insert       7     6       7     7

lcs_seq_distance() and relatives

The rest of RapidFuzz’s distance module: lcs_seq_distance() / lcs_seq_similarity() (longest common subsequence), indel_distance() / indel_similarity() (insertions and deletions only; the similarity is fuzz_ratio() / 100), and prefix_*() / postfix_*() (common prefix or suffix). All take (a, b, nthreads = NULL, use_bytes = FALSE).

lcs_seq_distance("kitten", "sitting")
[1] 3
indel_similarity("kitten", "sitting")
[1] 0.6153846
prefix_similarity(c("Johnson", "Johnston"), c("Johnston", "Jonson"))
[1] 0.625 0.250

editex() / editex_similarity()

Zobel and Dart’s Editex: an edit distance in which letters that sound alike cost less to swap, following the abydos and textdistance packages.

editex(c("Phillips", "Smith"), c("Filips", "Smyth"))
[1] 3 1
editex_similarity("Niall", "Neil")
[1] 0.8

lcs_str() / lcs_str_similarity()

The longest common substring (contiguous), choosing the one that starts earliest in a, as difflib’s find_longest_match() does.

lcs_str("acme holdings pty ltd", "acme holdings limited")
[1] "acme holdings "

smith_waterman()

Smith-Waterman local alignment with Gotoh’s affine gaps; the defaults reproduce SimMetrics’ SmithWatermanGotoh.

smith_waterman(a, b, match = 1, mismatch = -2, gap_open = -0.5,
               gap_extend = gap_open, normalize = TRUE, nthreads = NULL,
               use_bytes = FALSE)
smith_waterman("Dept of Health", "Queensland Health")
[1] 0.5

monge_elkan()

The mean, over the words of a[i], of the best similarity to a word of b[i] (Jaro-Winkler by default); symmetric = TRUE averages both directions.

monge_elkan(a, b, method = c("jaro_winkler", "levenshtein", "osa",
                             "damerau_levenshtein"),
            p = 0.1, symmetric = FALSE, nthreads = NULL, use_bytes = FALSE)
monge_elkan("Smith John", "Jon Smyth")
[1] 0.9133333
monge_elkan("Smith", "John Smith", symmetric = TRUE)
[1] 0.75

13.11 Q-gram similarity

jaccard_index(), dice_coefficient(), tversky_index(), and cosine_similarity() compare two strings’ overlapping length-q substrings (“q-grams”). All four share one sorted-merge pass over packed-integer q-grams without routing through stringdist’s generic R-level dispatch (sec-benchmarks). The first three compare q-gram sets (a repeated q-gram counts once); cosine_similarity() compares frequency profiles, so repetition carries weight.

jaccard_index()

jaccard_index(a, b, q = 2, nthreads = NULL, use_bytes = TRUE)
Argument Description
a, b Equal-length character vectors.
q Q-gram length (default 2, i.e. bigrams). Must be a single integer >= 1.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.
use_bytes Logical. Compare encoded bytes (TRUE) or UTF-8 code points (FALSE).

Returns: numeric vector of similarities in [0, 1], length(a) long. Two strings shorter than q (so neither has any q-grams) compare equal (1).

jaccard_index("night", "nacht")
[1] 0.1428571

jaccard_matrix()

All-pairs Jaccard similarity. Same argument/return shape as jaro_winkler_matrix().

jaccard_matrix(a, b, q = 2, nthreads = NULL, use_bytes = TRUE)

dice_coefficient() / dice_matrix()

The Sorensen-Dice coefficient: 2*|intersection| / (|A| + |B|). Weights shared q-grams more heavily than Jaccard (always >= the Jaccard score for the same pair). Same arguments as jaccard_index()/jaccard_matrix().

dice_coefficient("night", "nacht")
[1] 0.25

tversky_index() / tversky_matrix()

Generalises both: |intersection| / (|intersection| + alpha*|A only| + beta*|B only|). alpha = beta = 1 reduces to Jaccard; alpha = beta = 0.5 (the default) reduces to Dice.

tversky_index(a, b, q = 2, alpha = 0.5, beta = 0.5, nthreads = NULL,
              use_bytes = TRUE)
Argument Description
a, b, q, nthreads Same as jaccard_index().
alpha, beta Tversky asymmetry weights (default 0.5 each). Non-negative scalars.
use_bytes Logical. Compare encoded bytes (TRUE) or UTF-8 code points (FALSE).
tversky_index("night", "nacht", alpha = 1, beta = 1)   # == jaccard_index()
[1] 0.1428571
tversky_index("night", "nacht", alpha = 0.5, beta = 0.5) # == dice_coefficient()
[1] 0.25

cosine_similarity() / cosine_matrix()

Builds a q-gram frequency profile for each string and returns the cosine of the angle between the two profiles — dot(A, B) / (||A|| * ||B||). Repeated q-grams keep their multiplicity, which is the whole difference from the three set metrics above.

cosine_similarity(a, b, q = 2, nthreads = NULL, use_bytes = TRUE)
cosine_matrix(a, b, q = 2, nthreads = NULL, use_bytes = TRUE)
Argument Description
a, b, q, nthreads Same as jaccard_index()/jaccard_matrix().
use_bytes Logical. Compare encoded bytes (TRUE) or UTF-8 code points (FALSE).

Returns: numeric vector of similarities in [0, 1], length(a) long (or a length(a) × length(b) matrix). Missing comparisons return NA. If neither string has a q-gram the similarity is 1; if only one does, it is 0.

cosine_similarity("night", "nacht")
[1] 0.25
# Multiplicity: one distinct shared bigram, but different counts
cosine_similarity("aaaa", "aaab", q = 2)
[1] 0.8944272
jaccard_index("aaaa", "aaab", q = 2)
[1] 0.5
cosine_matrix(c("JOHN SMITH", "MARY JONES"), c("JON SMYTH", "MARY JONES"))
          [,1]      [,2]
[1,] 0.5892557 0.1111111
[2,] 0.2357023 1.0000000

13.12 RapidFuzz scorers

Vectorised ports of the scorers in Python’s RapidFuzz fuzz module, the maintained successor to fuzzywuzzy. Scores agree with rapidfuzz.fuzz to floating-point precision; see sec-theory for the algorithms.

fuzz_ratio(a, b, full_process = TRUE, score_cutoff = 0, nthreads = NULL)
fuzz_partial_ratio(a, b, full_process = TRUE, score_cutoff = 0, nthreads = NULL)
fuzz_token_sort_ratio(a, b, full_process = TRUE, score_cutoff = 0, nthreads = NULL)
fuzz_token_set_ratio(a, b, full_process = TRUE, score_cutoff = 0, nthreads = NULL)
fuzz_token_ratio(a, b, full_process = TRUE, score_cutoff = 0, nthreads = NULL)
fuzz_partial_token_sort_ratio(a, b, full_process = TRUE, score_cutoff = 0, nthreads = NULL)
fuzz_partial_token_set_ratio(a, b, full_process = TRUE, score_cutoff = 0, nthreads = NULL)
fuzz_partial_token_ratio(a, b, full_process = TRUE, score_cutoff = 0, nthreads = NULL)
fuzz_wratio(a, b, full_process = TRUE, score_cutoff = 0, nthreads = NULL)
fuzz_qratio(a, b, full_process = TRUE, score_cutoff = 0, nthreads = NULL)
fuzz_partial_ratio_alignment(a, b, full_process = TRUE, score_cutoff = 0, nthreads = NULL)
fuzz_default_process(x, nthreads = NULL)
Argument Description
a, b Equal-length character vectors.
full_process Logical (default TRUE). Runs both strings through fuzz_default_process() first: lowercase, every character that is not a letter or digit turned into a space, ends trimmed. This is RapidFuzz’s processor = utils.default_process; FALSE compares the strings as given, RapidFuzz’s own default.
score_cutoff Number in [0, 100] (default 0). Scores below it are returned as 0, and the scorers use it to stop early.
nthreads Positive integer per-call thread cap, or NULL for the RcppParallel default; 1 forces serial execution.

Returns: numeric vector of unrounded scores in [0, 100], length(a) long; NA where either input is NA. fuzz_partial_ratio_alignment() returns a data frame of the score and the 1-based positions of the aligned slices (src_start, src_end in a; dest_start, dest_end in b), and fuzz_default_process() the processed strings.

  • fuzz_ratio(): normalised Indel similarity, 200 * LCS / (len(a) + len(b)).
  • fuzz_partial_ratio(): the best fuzz_ratio() of the shorter string against any window of the longer one (found exactly).
  • fuzz_token_sort_ratio(): fuzz_ratio() of the sorted words.
  • fuzz_token_set_ratio(): compares shared words with each side’s extra words; 100 when one side’s words are a subset of the other’s.
  • fuzz_token_ratio(): the better of token sort and token set.
  • fuzz_partial_token_sort_ratio(), fuzz_partial_token_set_ratio(), fuzz_partial_token_ratio(): the same with the partial ratio.
  • fuzz_wratio(): RapidFuzz’s WRatio, a length-aware weighted best of the above.
  • fuzz_qratio(): fuzz_ratio(), but 0 when either string is empty.

The process module is ported as well. Each string is processed once, not once per pair, and the extract functions prune candidates that cannot make a query’s list:

fuzz_extract(x, choices, scorer = "wratio", limit = 5L, full_process = TRUE,
             score_cutoff = 0, nthreads = NULL)
fuzz_extract_one(x, choices, scorer = "wratio", full_process = TRUE,
                 score_cutoff = 0, nthreads = NULL)
fuzz_cdist(x, choices = x, scorer = "ratio", full_process = TRUE,
           score_cutoff = 0, nthreads = NULL)
fuzz_cpdist(a, b, scorer = "ratio", full_process = TRUE, score_cutoff = 0,
            nthreads = NULL)

scorer is a scorer’s name ("ratio", "token_set_ratio", "wratio", …; RapidFuzz spellings like "WRatio" work too) or the function itself. fuzz_extract() returns a long data frame (query_index, choice_index, choice, score, rank) of each query’s limit best choices (limit = NULL for all), with ties in table order. fuzz_extract_one() returns one row per query, NA when nothing reaches score_cutoff. fuzz_cdist() returns the full score matrix and fuzz_cpdist() element-wise scores.

fuzz_ratio("this is a test", "this is a test!")
[1] 100
fuzz_partial_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")
[1] 93.02326
fuzz_token_sort_ratio("fuzzy was a bear", "bear was a fuzzy")
[1] 100
fuzz_token_set_ratio("fuzzy was a bear", "fuzzy fuzzy bear was a bear")
[1] 100
fuzz_wratio("New York Mets", "The New York Mets baseball club")
[1] 90
fuzz_partial_ratio_alignment("a certain string", "cetain", full_process = FALSE)
     score src_start src_end dest_start dest_end
1 83.33333         3       8          1        6
teams <- c("Atlanta Falcons", "New York Jets", "New York Giants",
           "Dallas Cowboys")
fuzz_extract("new york jets", teams, limit = 2)
  query_index choice_index          choice     score rank
1           1            2   New York Jets 100.00000    1
2           1            3 New York Giants  78.57143    2
fuzz_extract_one(c("cowboys", "falcon"), teams)
           choice score choice_index
1  Dallas Cowboys    90            4
2 Atlanta Falcons    90            1
round(fuzz_cdist(c("new york", "dallas"), teams, scorer = "token_set_ratio"), 1)
     [,1]  [,2] [,3]  [,4]
[1,] 26.1 100.0  100  18.2
[2,] 38.1  10.5   19 100.0