Library contents

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

  1. Start with Keys A, B
  2. Do this Find B in the key list
  3. Result Position 2
R counts positions from one. The second key matches B.

Syntax

R 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.

From the programcat(paste(rates[index], collapse = " "), "\n", sep = "")
Result12 NA 8
Lesson.R
codes <- c("A", "B", "A")
rates <- c(8, 12, 99)
index <- match(c("B", "Z", "A"), codes)
cat(paste(rates[index], collapse = " "), "\n", sep = "")
Output
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.

R documentation for match

Advertisements

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?

Given4 · 9 · 15 · 22 | seek 15
Worked result2

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?

Given3 · 6 · 10 | seek 3
Worked result0