YouTip LogoYouTip

R Func Match

# R match() Function - Element Matching [![Image 3: R Language Examples](#) R Language Examples](#) The R match() function is used to find the first occurrence position of elements from one vector in another vector. match() is similar to the %in% operator, but returns positions instead of logical values. The syntax format of the match() function is as follows: match(x, table, nomatch = NA_integer_) **Parameter Description:** * **x** The vector of elements to look up. * **table** The target vector to be searched. * **nomatch** The value returned when matching fails, default is NA. ## Example # Find element positions fruits <-c("apple", "banana", "Orange", "Grape", "Watermelon") wanted <-c("banana", "Watermelon", "Lemon") # Find positions of elements in wanted within fruits positions <-match(wanted, fruits) print("Match Result:") print(positions) # Corresponding lookup: get actual values using positions print("Matched Fruit:") print(fruits[positions[!is.na(positions)]]) Execute the above code, the output result is: "Match Result:" 2 5 NA "Matched Fruit:" "banana" "Watermelon" match() is commonly used to reorder another data based on one vector: ## Example # 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 specific order wanted_order <-c("Wang Wu", "Zhao Liu", "Zhang San", "Li Si") idx <-match(wanted_order, names(scores)) print("Scores Arranged in Specified Order:") print(scores) Execute the above code, the output result is: "Scores Arranged in Specified Order:"Wang Wu Zhao Liu Zhang San Li Si 76 85 88 92 [![Image 4: R Language Examples](#) R Language Examples](#)
← R Func Min MaxR Func Log β†’