R match() Function - Element Matching
The R match() function is used to find the first occurrence position of elements in one vector within another vector.
match() is similar to the %in% operator, but returns positions rather than logical values.
The syntax of the match() function is as follows:
match(x, table, nomatch = NA_integer_)
Parameter Description:
xThe vector of elements to be searched for.
tableThe target vector to be searched.
nomatchThe value returned when matching fails, default NA.
Examples
# Find element positions
fruits <- c("apple", "banana", "orange", "grape", "watermelon")
wanted <- c("banana", "watermelon", "lemon")
# Find the positions of elements in wanted in fruits
positions <- match(wanted, fruits)
print("Matching results:")
print(positions)
# Corresponding lookup: use positions to get actual values
print("Fruits found:")
print(fruits[positions[!is.na(positions)]])
fruits <- c("apple", "banana", "orange", "grape", "watermelon")
wanted <- c("banana", "watermelon", "lemon")
# Find the positions of elements in wanted in fruits
positions <- match(wanted, fruits)
print("Matching results:")
print(positions)
# Corresponding lookup: use positions to get actual values
print("Fruits found:")
print(fruits[positions[!is.na(positions)]])
Executing the above code produces the following output:
[1] "匹配结果:" [1] 2 5 NA [1] "找到的水果:" [1] "香蕉" "西瓜"
match() is often used to reorder another data set based on one vector:
Examples
# Student grade table
student_names <- c("Zhang San", "Li Si", "Wang Wu", "Zhao Liu")
scores <- c(88, 92, 76, 85)
names(scores) <- student_names
# Arrange grades in a specific order
wanted_order <- c("Wang Wu", "Zhao Liu", "Zhang San", "Li Si")
idx <- match(wanted_order, names(scores))
print("Grades arranged in the specified order:")
print(scores[idx])
student_names <- c("Zhang San", "Li Si", "Wang Wu", "Zhao Liu")
scores <- c(88, 92, 76, 85)
names(scores) <- student_names
# Arrange grades in a specific order
wanted_order <- c("Wang Wu", "Zhao Liu", "Zhang San", "Li Si")
idx <- match(wanted_order, names(scores))
print("Grades arranged in the specified order:")
print(scores[idx])
Executing the above code produces the following output:
[1] "按指定顺序排列的成绩:" 王五 赵六 张三 李四 76 85 88 92Other Extensions
R Language Examples