Free-text fields hide structured values – a postcode at the end of an address, an amount in a description, a drug name in a case note. This chapter is about getting them out: flagging records that mention any of a long list of terms, tolerating misspellings, and extracting fields and numbers in one vectorised pass.
Task
Function
Instead of
Does the text mention any of N terms? Which? How often?
Keyword lists are long – medicines, product codes, place names, sanctions lists – and the obvious approaches scale badly: one grepl() per term reads the text once per term, and a single alternation of thousands of terms is slow for a backtracking regex engine. fgrepl_any() and its siblings build an Aho-Corasick automaton from the terms and read each string once, however many terms there are:
notes<-c("Pt given paracetamol 500mg and ibuprofen","Reports nausea after AMOXICILLIN course","No medication. Seen by police at home","Advised to stop taking aspirin; started warfarin","paracetemol 1g PRN","Discussed diet and exercise")drugs<-c("paracetamol", "ibuprofen", "amoxicillin", "aspirin", "warfarin","ice", "codeine")data.frame( any =fgrepl_any(drugs, notes, ignore.case =TRUE), first =drugs[fwhich_any(drugs, notes, ignore.case =TRUE)], count =fcount_any(drugs, notes, ignore.case =TRUE))
fwhich_any() reports the first term in the list that occurs, so the order of terms is a priority order – put the most specific or most serious terms first. fextract_any(all = TRUE) lists every occurrence.
Two things stand out. The terms are matched as substrings, so "ice" (the street name for methamphetamine) is found inside "police". Pad both sides with spaces to match whole words only:
fagrepl() is agrepl() – the same arguments and the same results – computed with Myers’ bit-parallel algorithm on every core. It finds the pattern anywhere in each string within max.distance edits:
For a list of terms, call it once per term; it is fast enough that a few hundred terms over a million notes is practical. When the question is “which dictionary entry is this whole value closest to”, use fuzzy_within() instead (sec-uc-link).
4.3 Extract values with regular expressions
fextract() returns the first match per string, or one capture group of it; fextract_all() returns every match. Here are the state and postcode at the end of an Australian address:
addr<-c("12 Smith St, Brisbane QLD 4000", "Unit 3, 45 North Rd, Darwin NT 0800","PO Box 99, Hobart TAS 7001", "No postcode here")data.frame( state =fextract("\\b(NSW|QLD|VIC|SA|WA|TAS|NT|ACT)\\s+[0-9]{4}$", addr, group =1), postcode =fextract("\\b(NSW|QLD|VIC|SA|WA|TAS|NT|ACT)\\s+([0-9]{4})$", addr, group =2))
state postcode
1 QLD 4000
2 NT 0800
3 TAS 7001
4 <NA> <NA>
And every phone number or email address in a message:
Patterns follow the same rules as fgrepl(): base R’s extended regular expressions by default, PCRE with perl = TRUE, literal text with fixed = TRUE. Strings with no match give NA (or character(0) from fextract_all()), so the result lines up with the input row for row.
4.4 Split delimited fields
fsplit_field() returns one field of delimited text without building the list that strsplit() would, which matters when you only want one or two fields of millions of rows:
full<-c("SMITH, John Paul", "O'BRIEN, Mary", "NGUYEN,Van Anh", "MADONNA")data.frame(full, surname =fsplit_field(full, ",", 1, fixed =TRUE), given =fsquish(fsplit_field(full, ",", 2, fixed =TRUE)))
full surname given
1 SMITH, John Paul SMITH John Paul
2 O'BRIEN, Mary O'BRIEN Mary
3 NGUYEN,Van Anh NGUYEN Van Anh
4 MADONNA MADONNA <NA>
state postcode last
1 QLD 4000 BRISBANE
2 NSW 2000 CBD
3 VIC MELBOURNE
Every field counts, including empty ones ("VIC||MELBOURNE" has an empty postcode), and negative positions count from the end.
4.5 Numbers inside text
Amounts typed into free-text or spreadsheet columns come with currency symbols, thousands separators, units and labels. fparse_number() finds the first number in each string and ignores the rest:
prices<-c("$1,234.50", "AUD 99", "12.5%", "approx. 3,000 kg", "-$45.10","(1,200)", "N/A", "Free")out<-data.frame(prices, fparse_number =fparse_number(prices), gsub =suppressWarnings(as.numeric(gsub("[^0-9.-]", "", prices))))# readr is not a dependency of this package; compare against it when it# happens to be installed.if(requireNamespace("readr", quietly =TRUE))out$readr<-suppressWarnings(readr::parse_number(prices))out
prices fparse_number gsub
1 $1,234.50 1234.5 1234.5
2 AUD 99 99.0 99.0
3 12.5% 12.5 12.5
4 approx. 3,000 kg 3000.0 0.3
5 -$45.10 -45.1 -45.1
6 (1,200) 1200.0 1200.0
7 N/A NA NA
8 Free NA NA
The common shortcut of deleting everything but digits fails as soon as the text contains another full stop ("approx." becomes 0.3). readr::parse_number() returns NA for that case and for a minus sign in front of a currency symbol, and (in our tests) rounds about a quarter of two-decimal amounts to a neighbouring double; fparse_number() returns exactly what as.numeric() gives for the number it finds. Accounting-style negatives such as "(1,200)" are read as positive by both, so test for the parentheses separately if your data uses them. Other conventions are one argument away: