Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R match() Function - Element Matching

R match() Function - Element Matching

R Language Examples R Language Examples

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:

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

)

print

(

"Matching result:"

)

print

(

positions

)

Corresponding lookup: Use positions to get actual values

print

(

"Fruits found:"

)

print

(

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

)

)

print

(

"Scores arranged in the specified order:"

)

print

(

scores

[

idx

]

)

The output of the code above is:

[1] "按指定顺序排列的成绩:"

王五 赵六 张三 李四

 76   85   88   92

R Language Examples R Language Examples