在 R 编程中查找向量之间匹配元素的位置 – match()函数
R语言中的match()
函数用于返回第一个向量的元素在第二个向量中的第一个匹配的位置。如果未找到该元素,则返回 NA。
Syntax: match(x1, x2, nomatch)
Parameters:
x1: Vector 1
x2: Vector 2
nomatch: value to be returned in case of no match
示例 1:
# R program to match the vectors
# Creating vectors
x1 <- c("a", "b", "c", "d", "e")
x2 <- c("d", "f", "g", "a", "e", "k")
# Calling match function
match(x1, x2)
输出:
[1] 4 NA NA 1 5
示例 2:
# R program to match the vectors
# Creating vectors
x1 <- c("a", "b", "c", "d", "e")
x2 <- c("d", "f", "g", "a", "e", "k")
# Calling match function
match(x1, x2, nomatch = "-1")
输出:
[1] 4 -1 -1 1 5