match()
match(x, table, nomatch = NA_integer_, incomparables = FALSE) Returns:
integer · Updated March 13, 2026 · Base Functions base matching vectors
match() returns the position of the first match between elements of x in table.
Syntax
match(x, table, nomatch = NA_integer_, incomparables = FALSE)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | vector | — | The values to look up |
table | vector | — | The values to match against |
nomatch | integer | NA_integer_ | Value to return when no match is found |
incomparables | vector | FALSE | Values in x that cannot be matched |
Examples
Basic usage
x <- c("a", "b", "c", "d")
table <- c("b", "c", "e")
match(x, table)
# [1] NA 1 2 NA
Using nomatch parameter
match(c("apple", "cherry"), c("apple", "banana"), nomatch = 0)
# [1] 1 0
Finding unique or duplicate values
new_values <- c("apple", "banana", "cherry", "apple")
seen <- c("apple", "banana")
# Get indices of matches
idx <- match(new_values, seen)
idx
# [1] 1 2 NA 1
Practical data cleaning
df <- data.frame(
category = c("A", "B", "C", "D", "A"),
value = 1:5
)
allowed <- c("A", "B")
idx <- match(df$category, allowed)
idx
# [1] 1 2 NA NA 1
Common Patterns
Deduplication: Identify which values in one vector appear in another:
existing_ids <- c(101, 102, 103)
new_ids <- c(101, 104, 105, 103)
# Which new IDs already exist?
!is.na(match(existing_ids, new_ids))
# [1] TRUE FALSE FALSE
# Get only the new IDs
setdiff(new_ids, existing_ids)
# [1] 104 105