R match() Function - Element Matching
The R match() function is used to find the position of the first occurrence of elements of one vector in another vector.
match() is similar to the %in% operator, but returns positions instead of logical values.
The syntax of the match() function is as follows:
match(x, table, nomatch = NA_integer_)
Parameter Description:
-
x The vector of elements to find.
-
table The target vector to search in.
-
nomatch The value returned when no match is found, default NA.
Example
Find element positions
fruits
<-
c
(
"Apple"
,
"Banana"
,
"Orange"
,
"Grape"
,
"Watermelon"
)
wanted
<-
c
(
"Banana"
,
"Watermelon"
,
"Lemon"
)
Find the positions of elements in wanted within fruits
positions
<-
match
(
wanted, fruits
)
(
"Matching result:"
)
(
positions
)
Corresponding lookup: Use positions to get actual values
(
"Fruits found:"
)
(
fruits
[
positions
[
!
is.na
(
positions
)
]
]
)
The output of the code above is:
[1] "匹配结果:"
[1] 2 5 NA
[1] "找到的水果:"
[1] "香蕉" "西瓜"
match() is often used to rearrange one data based on another vector:
Example
Student score table
student_names
<-
c
(
"Zhang San"
,
"Li Si"
,
"Wang Wu"
,
"Zhao Liu"
)
scores
<-
c
(
88
,
92
,
76
,
85
)
names
(
scores
)
<-
student_names
Arrange scores in a specific order
wanted_order
<-
c
(
"Wang Wu"
,
"Zhao Liu"
,
"Zhang San"
,
"Li Si"
)
idx
<-
match
(
wanted_order,
names
(
scores
)
)
(
"Scores arranged in the specified order:"
)
(
scores
[
idx
]
)
The output of the code above is:
[1] "按指定顺序排列的成绩:"
王五 赵六 张三 李四
76 85 88 92
R Language Examples