R match
match returns the first position of each lookup value in a table. Its default missing result is NA_integer_.
A simple example
match
- Start with Keys A, B
- Do this Find B in the key list
- Result Position 2
Syntax
index <- match(keys, reference)
Run this example in R
Save the program as Lesson.R. Use R 4.x.
Rscript --vanilla Lesson.R
Join item labels to the first matching rate
An export contains keys that may identify more than one input record. Establish what happens at a repeated key before constructing the lookup so useful records are not discarded unintentionally.
codes <- c("A", "B", "A")
rates <- c(8, 12, 99)
index <- match(c("B", "Z", "A"), codes)
cat(paste(rates[index], collapse = " "), "\n", sep = "")
12 NA 8
Repeated reference keys resolve to the first position. Indexing the rates vector with an unmatched position propagates NA, exposing an incomplete lookup table.
Locate a numbered tote
A parcel clerk keeps tote numbers in ascending order. Find the specified item in the sorted register. How many smaller entries come before it?
Find the earliest permit
A permit clerk starts with the smallest valid identifier. Find the specified item in the sorted register. How many smaller entries come before it?